Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to use "attribute value templates" in variable or param?

Tags:

xslt

this is nice and short:

<img src="{$base}/{@filename}.jpg" />

but sometimes you need to reuse the src, so it turns into this:

<xsl:variable name="imgsrc">
    <xsl:value-of select="$base">/<xsl:value-of select="@filename">
    <xsl:text>.jpg</xsl:text>
</xsl:variable>
<img src="$imgsrc" />

According to http://www.w3.org/TR/xslt#dt-attribute-value-template you can't use the "curly brackets interpolation syntax" outside of literal element attributes, but there might be a not-so-hacky hack to do the trick? I'm lazy, I know.

like image 546
kubi Avatar asked Aug 05 '13 15:08

kubi


People also ask

What is difference between Param and variable in XSLT?

The difference is that the value of an xsl:param could be set outside the context in which it is declared.

How do you use variables in XSLT?

XSLT <xsl:variable>The <xsl:variable> element is used to declare a local or global variable. Note: The variable is global if it's declared as a top-level element, and local if it's declared within a template. Note: Once you have set a variable's value, you cannot change or modify that value!

How do I apply a template in XSLT?

The <xsl:apply-templates> element applies a template to the current element or to the current element's child nodes. If we add a "select" attribute to the <xsl:apply-templates> element, it will process only the child elements that matches the value of the attribute.

What is attribute in XSLT?

XSLT <xsl:attribute> The <xsl:attribute> element is used to add attributes to elements. Note: The <xsl:attribute> element replaces existing attributes with equivalent names.


2 Answers

You can use a select expression to define the variable, using the concat function to join the various bits together:

<xsl:variable name="imgsrc" select="concat($base, '/', @filename, '.jpg')"/>
<img src="{$imgsrc}" />

This is also more efficient than the <xsl:value-of> approach because by using select you're setting the variable to a string value directly rather than creating a tree fragment containing a text node which then has to be converted back into a string when you reference the variable.

like image 91
Ian Roberts Avatar answered Oct 13 '22 16:10

Ian Roberts


XSLT 3.0 contains some goodies in this area:

(a) a concat operator

select="$base || '/' || @filename || '.jpg'

(b) "text value templates"

<xsl:variable name="x">{$base}/{@filename}/.jpg</xsl:variable>

(which needs to be enabled, for compatibility reasons)

like image 28
Michael Kay Avatar answered Oct 13 '22 14:10

Michael Kay