In XSLT 1.0, what is the shortest/cleanest/recommended way to pass the current context node to a called template and have that node become the context node inside the called template?
It would be nice (it would, right?) if a template with no xsl:param and called by an empty call-template would simply pick up the caller's context node, but the best I can think of is this:
<xsl:call-template name="sub"> <xsl:with-param name="context" select="." /> </xsl:call-template>
with
<xsl:template name="sub"> <xsl:param name="context" /> <xsl:for-each select="$context"> </xsl:for-each> </xsl:template>
Returns the contents of the current group selected by xsl:for-each-group. Available in XSLT 2.0 and later versions. Available in all Saxon editions. current-group() ➔ item()*
With <xsl:apply-templates> the current node moves on with every iteration, whereas <xsl:call-template> does not change the current node.
Specifies the format pattern. Here are some of the characters used in the formatting pattern: 0 (Digit) # (Digit, zero shows as absent)
To use an XSLT parameterCreate an XsltArgumentList object and add the parameter using the AddParam method. Call the parameter from the style sheet.
It would be nice (it would, right?) if a template with no
xsl:param
and called by an emptycall-template
would simply pick up the caller's context node.
This is exactly how xsl:call-template
is defined in the W3C XSLT 1.0 (and 2.0) specification, and implemented by any compliant XSLT processor.
Here is a small example:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="a"> <xsl:call-template name="currentName"/> </xsl:template> <xsl:template name="currentName"> Name: <xsl:value-of select="name(.)"/> </xsl:template> </xsl:stylesheet>
When this transformation is applied on the following XML document:
<t> <a/> </t>
the wanted, correct result is produced:
Name: a
Just otherway of explaining what Dimitre said.
When you call a template from a node, you are already there in that node,
example:
assume this code:
<xsl:template match="MyElement"> <xsl:call-template name="XYZ"/> </xsl:template> <xsl:template name="XYZ> <xsl:value-of select="."/> </xsl>
The above code is as good as writing:
<xsl:template match="MyElement"> <xsl:value-of select="."/> </xsl:template>
You can use for-each loop in the called template as well. :)
But just be sure where you exactly are ..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With