XSLT - named templates in XSLT.

What are Named Templates?

  • A named template is defined with <xsl:template name="...">.

  • You can invoke it explicitly using <xsl:call-template name="..."/>.

  • Unlike match templates, which run automatically when a node matches, named templates are called on demand.

  • They can accept parameters (<xsl:param>) and work like reusable functions.

 Syntax

Defining

<xsl:template name="templateName">
    <!-- instructions -->
</xsl:template>

Calling

<xsl:call-template name="templateName"/>

Passing Parameters

<xsl:call-template name="templateName">
    <xsl:with-param name="param1" select="'value'"/>
</xsl:call-template>

 Example 1: Simple named template

XML

<message>Hello World</message>

XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  
  <xsl:template match="/">
    <html>
      <body>
        <xsl:call-template name="printMessage"/>
      </body>
    </html>
  </xsl:template>

  <!-- Named template -->
  <xsl:template name="printMessage">
    <h2><xsl:value-of select="message"/></h2>
  </xsl:template>

</xsl:stylesheet>

Output

<html>
  <body>
    <h2>Hello World</h2>
  </body>
</html>

 Example 2: Named template with parameters

XML

<data/>

XSLT

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">

  <xsl:template match="/">
    <html>
      <body>
        <!-- Call template with parameters -->
        <xsl:call-template name="greet">
          <xsl:with-param name="name" select="'Alice'"/>
        </xsl:call-template>
        <br/>
        <xsl:call-template name="greet">
          <xsl:with-param name="name" select="'Bob'"/>
        </xsl:call-template>
      </body>
    </html>
  </xsl:template>

  <!-- Named template with parameter -->
  <xsl:template name="greet">
    <xsl:param name="name"/>
    Hello, <xsl:value-of select="$name"/>!
  </xsl:template>

</xsl:stylesheet>

Output

<html>
  <body>
    Hello, Alice!<br/>Hello, Bob!
  </body>
</html>

Example 3: Named template with recursion

Named templates are often used for recursion (like factorial or summing numbers).

<xsl:template name="countdown">
  <xsl:param name="n"/>
  <xsl:value-of select="$n"/>
  <xsl:if test="$n &gt; 1">
    <xsl:text>, </xsl:text>
    <xsl:call-template name="countdown">
      <xsl:with-param name="n" select="$n - 1"/>
    </xsl:call-template>
  </xsl:if>
</xsl:template>

Calling it with:

<xsl:call-template name="countdown">
  <xsl:with-param name="n" select="5"/>
</xsl:call-template>

Output:

5, 4, 3, 2, 1

Summary:

  • Named templates are like functions in XSLT.

  • Use <xsl:call-template> to invoke them.

  • They can take parameters and even call themselves (recursion).

  • Great for modular, reusable code.