Jim Maivald
Jim Maivald

Reputation: 520

Changing image path using XSLT

I am converting an XML data output to HTML using XSLT 1.0. The data is being exported from Adobe InDesign and generates an absolute link to the image location on the user's computer. However, the final HTML file will be used for an HTML-based email system. The absolute link to the images needs to be converted to a relative link. Is it possible to convert any absolute link to a web based image file to a specific relative link?

The XML image element will look like this:

<generic_image  href="file:///MacProjects/Workflow/New%20Sample%20Data/Email_test_7-5/Surfaces/Images/Combo_logo_LO.png"></generic_image>

The desired HTML image output should look like this:

<img class="image" src="Images/Combo_logo_LO.png" style="max-width: 80%;">

My XSL template currently looks like this:

<xsl:template match="generic_image"><img class="image" src="{@href}" style="max-width: 80%;" /></xsl:template>

How can I pull just the image name from the data and create the appropriate relative path?

FYI, the absolute image can vary based on the user, so it could be different than the one shown. It can also come from Mac or Windows computers.

Upvotes: 0

Views: 1097

Answers (1)

Loic
Loic

Reputation: 2193

You can use a recursive template combined with the substring-after function. The underlaying idea is to extract whatever string after the "/" as long as any is found.

<xsl:template match="generic_image">
        <xsl:call-template name="getFileName">
            <xsl:with-param name="url">
                <xsl:value-of select="@href"/>
            </xsl:with-param>
        </xsl:call-template>
    </xsl:template>
    
    <xsl:template name="getFileName">
        <xsl:param name="url"/>
        <xsl:choose>
            <xsl:when test="contains($url, '/')">
                <xsl:call-template name="getFileName">
                    <xsl:with-param name="url">
                        <xsl:value-of select="substring-after($url, '/')"/>
                    </xsl:with-param>
                </xsl:call-template>
            </xsl:when>
            <xsl:otherwise>
                <img class="image" src="{$url}" style="max-width: 80%;" /> 
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>

Upvotes: 1

Related Questions