xsl:call-template

  1. call-template_1-input.xml

  2. <?xml version="1.0"?>
  3. <products>
  4.   <product id="p1" price="3250" stock="4"/>
  5.   <product id="p2" price="1000" stock="5"/>
  6. </products>
  1. call-template_1-stylesheet.xsl

  2. <?xml version="1.0"?>
  3. <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
  4.   <xsl:output indent="yes"/>
  5.   <xsl:template match="/">
  6.     <Products><xsl:apply-templates/>
  7.     <Updated>
  8.       <xsl:call-template name="today"/>
  9.     </Updated>
  10.     </Products>
  11.   </xsl:template>
  12.   <xsl:template match="product">
  13.     <Product id="{@id}" price="{@price}" stock="{@stock}"/>
  14.   </xsl:template>
  15.   <xsl:template name="today">
  16.     <xsl:value-of select="format-date(current-date(), '[Y]-[M01]-[D01]')"/>
  17.   </xsl:template>
  18. </xsl:stylesheet>
  1. call-template_1-output.xml

  2. <?xml version="1.0" encoding="UTF-8"?>
  3. <Products>
  4.   <Product id="p1" price="3250" stock="4"/>
  5.   <Product id="p2" price="1000" stock="5"/>
  6.   <Updated>2009-03-08</Updated>
  7. </Products>

Comment

The third template has a name attribute instead of a match attribute. A named template works much like a user-defined function returning something. When using xsl:call-template it is very common also to send parameters with the call, see: xsl:with-param.

Now when we have a named template called "today", we can transfer it to an XSLT template library that can be included in many stylesheets.

The main problem with named template is that we can't call it from an attribute. That is we have no access to it from an XPath expression. In XSLT 2.0 we can use xsl:function to make user-defined functions but xsl:call-template is still popular especially for returning markup.

Updated 2009-03-19