[Contents] [Prev] [Next] [Index] [Report an Error]

Named Templates

Named templates operate like functions in traditional programming languages, although with a verbose syntax. When markup grows complex, and when it appears in several different places in a style sheet, you can turn it into a named template. Named templates resemble variables. However, they enable you to include data from the place where the template is applied, rather than merely inserting fixed text.

Parameters can be passed into named templates, and the parameters can be declared with default values. The following sample template named my-template defines three parameters, one of which defaults to the string false, and one of which defaults to the contents of the element node named name that is a child of the current context node. If the template is called without values for these parameters, the default values are used. As with unnamed templates, the select attribute can contain any XPath expression. If no select attribute is given for a parameter, it defaults to an empty value.

<xsl:template name="my-template">
    <xsl:param name="a"/>
    <xsl:param name="b" select="'false'"/>
    <xsl:param name="c" select="name"/>
        <!- - ... body of the template goes here ... - ->
</xsl:template>

To invoke a named template, you must use the <xsl:call-template> element. It has a required name parameter that names the template it calls. When processed, the <xsl:call-template> element is replaced by the contents of the <xsl:template> element it names. In the following example, the template my-template is called with the parameter c containing the contents of the element node named other-name that is a child of the current context node.

<xsl:call-template name="my-template">
    <xsl:with-param name="c" select="other-name"/>
</xsl:call-template>

For an example showing how to use named templates in a commit script, see Requiring and Restricting Configuration Statements.


[Contents] [Prev] [Next] [Index] [Report an Error]