Forum Moderators: open
My XML template tree goes as follows:
<images>
<image>
<id>001</id>
<name>Image 1</name>
<caption>Some text describing this image</caption>
<url>image1.png</url>
</image>
</images>
Now, in my XSL document I need a global variable which will define the base directory for my images. Something along the lines of:
<xsl:variable name="ImgLoc1" select="images/colorschemes/red/" />
Then I need to somehow pass this together with my image name as an alt tag into the <img> tag.
I was thinking of something like:
<xsl:template match="images/">
<xsl:for-each select="image">
<img src="{$ImgLoc}<xsl:value-of select="name" />" alt="<xsl:value-of select="url" />">
</xsl:for-each>
</xsl:template>
But obviously it doesn't work as the syntax is obviously all wrong, how do I get the node values to pass as both image path and alt attribute?
Thanx!
<xsl:variable name="ImgLoc1" select="images/colorschemes/red/" />Presumably what you want here is for the value of the variable to be set to the text of "images/colorschemes/red/" and not an XML element <red> which is a child of <colorschemes> which is a child of <images>. If so, you need to quote the text so it doesn't get interpreted as an XPath:
<xsl:variable name="ImgLoc1" select="'images/colorschemes/red/'" />If you actually did want the XPath, the trailing slash is incorrect (see below); you want
<xsl:variable name="ImgLoc1" select="images/colorschemes/red" />
Now on to the template.
I was thinking of something like:
<xsl:template match="images/">
<xsl:for-each select="image">
<img src="{$ImgLoc}<xsl:value-of select="name" />" alt="<xsl:value-of select="url" />">
</xsl:for-each>
</xsl:template>
<xsl:template match="image">should suffice or if you have coding guidelines that require you to start at the root element,
<xsl:template match="images/image">works just as well.
In your output, you have element nodes appearing inside attributes, which is not valid XML. You have used the bracket notation correct to insert the value of a variable into an attribute; you can use the same notation to insert node values. You could also use the verbose <xsl:attribute> syntax which may make more clear what the processor sees and does:
<img src="{$ImgLoc}{url}" alt="{caption}" />
<img>
<xsl:attribute name="src">
<xsl:value-of select="$ImgLoc" />
<xsl:value-of select="url" />
</xsl:attribute>
<xsl:attribute name="alt">
<xsl:value-of select="caption" />
</xsl:attribute>
</img>