daniely
daniely

Reputation: 7733

Use same XSLT code multiple times in same file

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?

Upvotes: 1

Views: 1058

Answers (1)

Sean B. Durkin
Sean B. Durkin

Reputation: 12729

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.

Upvotes: 3

Related Questions