Previous | Next | Indexes
Zvon > Tutorials > XSLT 2.0 Tutorial > Context (6/6) >

Template context via variable

If context is changed in the template (e.g. by usage of xsl:for-each element), the function current() returns the changed context, not the context of the containing template.

If the template context is needed it may be saved to a variable and then used.

XSLT

      <xsl:stylesheet
                  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                  version="2.0">
            <xsl:output  method="xml"
                        indent="yes"
                        omit-xml-declaration="yes"/>

            <xsl:template  match="/aaa">
                  <xsl:apply-templates  select="bbb"/>
            </xsl:template>

            <xsl:template  match="bbb">
                  <xsl:variable  name="a"
                              select="."/>
                  <xsl:for-each  select="/aaa/ccc">
                        <iii>
                              <xsl:copy-of  select="."/>
                              <xsl:copy-of  select="current()"/>
                              <xsl:copy-of  select="$a"/>
                        </iii>
                  </xsl:for-each>
            </xsl:template>

      </xsl:stylesheet>
XML

      <aaa>
            <bbb>B1</bbb>
            <bbb>B2</bbb>
            <ccc>C1</ccc>
            <ccc>C2</ccc>
            <ccc>C3</ccc>
      </aaa>
Output

      <iii>
            <ccc>C1</ccc>
            <ccc>C1</ccc>
            <bbb>B1</bbb>
      </iii>
      <iii>
            <ccc>C2</ccc>
            <ccc>C2</ccc>
            <bbb>B1</bbb>
      </iii>
      <iii>
            <ccc>C3</ccc>
            <ccc>C3</ccc>
            <bbb>B1</bbb>
      </iii>
      <iii>
            <ccc>C1</ccc>
            <ccc>C1</ccc>
            <bbb>B2</bbb>
      </iii>
      <iii>
            <ccc>C2</ccc>
            <ccc>C2</ccc>
            <bbb>B2</bbb>
      </iii>
      <iii>
            <ccc>C3</ccc>
            <ccc>C3</ccc>
            <bbb>B2</bbb>
      </iii>


Previous chapter: Modes
Next chapter: Implicit behaviour
Previous page: Template context in XPath expressions - function current
Next page: - - -