XSLT » Elements » xsl:template

Syntax:
<xsl:template
  match="pattern"
  mode="qname"
  name="qname"
  priority="number"
>
</xsl:template>

The xsl:template element is used to define a template that can be applied to a node to produce a desired output display.

There must be either a match or name attribute, or both, and this determines how the template rule can be invoked. If there is only a match attribute, then you can use the xsl:apply-template element to invoke the template rule defined by the xsl:template element. If there is only a name attribute, then you can use the xsl:call-template element to invoke the named template defined by the xsl:template element. If both attributes are present, then you may invoke the template by either procedure.
 
It is quite possible that more than one template can be applied to a node. The highest priority value template is always chosen. If more than one suitable template has the same highest priority value, then the XSLT processor usually chooses the one that appears last. Different templates can not have both the same name and priority values. This is an error.
 
The xsl:template element is always a child of either the xsl:stylesheet or xsl:transform elements.
 
This is not a self-closing element. The separate closing element is mandatory.

Examples

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

<xsl:template match="devguru_staff/programmer">
<html>
<body>
<xsl:apply-templates select="name" />
<xsl:apply-templates select="dob" />
<xsl:apply-templates select="age" />
<br />
</body>
</html>
</xsl:template>

<xsl:template match="name">
<span style="font-size=22px;">
<xsl:value-of select="." />
</span>
<br />
</xsl:template>

<xsl:template match="dob">
DOB:<span style="color:blue;">
<xsl:value-of select="." />
</span>
<br />
</xsl:template>

<xsl:template match="age">
AGE:<span style="color:green;">
<xsl:value-of select="." />
</span>
<br />
</xsl:template>

</xsl:stylesheet>
Output:
Bugs Bunny
DOB: 03/21/1970
AGE: 31

Daisy Duck
DOB: 08/09/1949
AGE: 51

Minnie Mouse
DOB: 04/13/1977
AGE: 24

Pluto
DOB: 07/04/1979
AGE: 21

Porky Pig
DOB: 11/30/1956
AGE: 44

Road Runner
DOB: 01/19/1953
AGE: 48
Explanation:

In this example we create three different templates and apply them in the desired order in a fourth template using the xsl:apply-templates element. This is the code for xslt_example_template.xsl.
 
We use the DevGuru Staff List XML file for our example with the following header:
<?xml-stylesheet type="text/xsl" href="xslt_example_template.xsl"?>

Language(s): XSLT

See Also: