|Chapter 4 - Templates Rule!|
|XSLT For Dummies|
|by Richard Wagner|
|Hungry Minds 2002|
A named template is an xsl:template element that has a name attribute but no defined match attribute. Normally, you declare a match attribute for a template rule so that when the processor encounters the rule, it processes the rule immediately based on this match pattern. In contrast, a named template doesnt contain a match attribute, so another template or instruction using xsl:call-template must explicitly call a named template.
To demonstrate , I use the miniscore.xml (refer to Listing 4-3) as the source. Suppose I want to append a text string to several of the template rules I apply to the source document. Rather than adding the same text string to each of the template rules, I can instead create a single named template that is called by each of the template rules and have the named template actually do the real work. Consider the following XSLT stylesheet:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template name="CreditLine"> <xsl:value-of select="."/> - Brought to you by Tumplates, The Template People. </xsl:template> <xsl:template match="film"> Film: <xsl:call-template name="CreditLine"/> </xsl:template> <xsl:template match="composer"> Composer: <xsl:call-template name="CreditLine"/> </xsl:template> <xsl:template match="year"/> <xsl:template match="grade"/> </xsl:stylesheet>
The first xsl:template element is the named template. When called, it adds text to the result document using xsl:value-of . However, without a match attribute defined, the XSLT processor has nothing to evaluate so the processor ignores the named template unless its explicitly called somewhere else.
The next two template rules then use xsl:call-template to call the CreditLine named template, which executes based on the node set returned from the calling templates match pattern. The output then looks like:
Film: A Little Princess - Brought to you by Tumplates, The Template People. Composer: Patrick Doyle - Brought to you by Tumplates, The Template People.
Tip To find out how to use named templates in combination with parameters, see Chapter 8.