Table of Contents

XSLT - Templates

About

A stylesheet contains a number of templates, defined with the <xsl:template> tag.

An XSLT template is a set of formatting instructions that apply to the nodes selected by an XPath expression.

Syntax

In a stylesheet, an XSLT template would look something like this:

Without parameter

<xsl:template match="/ARTICLE/SECT">
 <h2> 
     <xsl:apply-templates select="text()|B|I|U|DEF|LINK"/> 
 </h2>
 <xsl:apply-templates select="SECT|PARA|LIST|NOTE"/> 
</xsl:template>

where:

With parameter

The definition

The parameterized template gets executed only when you invoke it.

<xsl:template name="htmLink">
 <xsl:param name="dest" select="UNDEFINED"/> 
 <xsl:element name="a">
    <xsl:attribute name="href">
       <xsl:value-of select="$dest"/>
    </xsl:attribute>
    <xsl:apply-templates/> 
 </xsl:element> 
</xsl:template>

where:

The call

<xsl:call-template name="htmLink">
  <xsl:with-param name="dest" select="@target"/> 
</xsl:call-template>

The template definition must be below the call.

Processing

A processor will process the stylesheet.

Tag

XSLT works by transforming the source tree into the result tree. To visualize the result of XSLT operations, it is helpful to understand the structure of those trees, and their contents.

Within the template, tags that do not start with the xsl: namespace prefix are simply copied. The newlines and whitespace that follow them are also copied.

An XSLT stylesheet expects to process tags. So everything it sees needs to be either:

In the example above case, the non-XSL tags are HTML tags. So when the root tag is matched, XSLT:

Order

Templates are independent of one another, so it does not generally matter where they occur in a file.

Order does make a difference when two templates can apply to the same node. In that case, the one that is defined last is the one that is found and processed.