1

I have some XSLT code like following

    <xsl:choose>
      <xsl:when test="v:Values = 'true'">
        <xsl:text>A</xsl:text>
      </xsl:when>
      <xsl:otherwise>
        <xsl:text>B</xsl:text>
      </xsl:otherwise>
...
    </xsl:choose>

I want to use this chunk of code many times in the same file. Can I put it in a template and call it when needed?

1

1 Answer 1

3

Yes - It's called xsl:call-template .

Any template can be given a name. The name can be qualified by a namespace. For example...

<xsl:template match="some match condition" name="call-me">
  bla bla bla (template content)
</xsl:template>

If the template has a name, it you can even omit the match condition like so...

<xsl:template name="call-me">
 <xsl:param name="phone-number" />
  bla bla bla (template content)
</xsl:template>

Named templates have as many parameters as you like. The above fragment is an example of declaring one parameter named phone-number. Within the template's sequence constructor, you will refer to this parameter, in the same manner as a variable, like so...

$phone-number

To invoke a named-template, use xsl:call-template from within a sequence constructor. For example ...

<xsl:call-template name="call-me">
 <xsl:with-param name="phone-number" select="'55512345678'" />
</xsl:template>

Notice that xsl:with-param is used to pass actual parameter value.

Note that in XSLT 2.0 you can also define functions callable from within XPATH expressions. In some circumstances, functions may be a better alternative to named templates.

Refer:

  1. XSLT 2.0 spec re.: named templates.
  2. XSLT 1.0 spec re.: named templates.
Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to change the context node when calling a template? This is necessary since inside the template, I use only relative xpath.
Yes. xsl:apply-templates and xsl:for-each both change the context node. For more details in answer, provide more details in question.
I found a workaround to the problem. Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.