Templates à la mode
The XSLT <xsl:template> element has a mode attribute
that lets you process the same set of nodes several times. For
example, we might want to process <h1> elements one way when we generate
a table of contents, and another way when we process the document as a
whole. We could use the mode
attribute to define different templates for different purposes:
<xsl:template match="h1" mode="build-toc"> <!-- Template to process the <h1> element for table of contents --> </xsl:template> <xsl:template match="h1" mode="process-text"> <!-- Template to process the <h1> element along with the rest --> <!-- of the document --> </xsl:template>
We can then start applying templates with the mode attribute:
<xsl:template match="/">
<html>
<body>
<h1>Table of Contents</h1>
<ul>
<xsl:apply-templates select="h1" mode="build-toc"/>
</ul>
<xsl:apply-templates select="*" mode="process-text"/>
</body>
</html>
</xsl:template>This style of coding makes maintenance much easier; if the table
of contents isn’t generated correctly, the templates with mode="build-toc" are the obvious place to
start debugging. (We discuss the mode attribute in more detail in the section
New values for the mode attribute” later in this
chapter.)
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access