XML technologies / XSLT / XSLT Kochbuch / Making the most of XSLT 2.0 / Modularization and modes

(Excerpt from "XSLT Kochbuch" by Sal Mangano)

Problem

XSLT 1.0’s restrictions on using modes often led to duplicated code or extra work.

Solution

Use the capabilities of the new XSLT 2.0 attribute mode to eliminate duplicated code. Consider a simple stylesheet that uses two different modes to process a document in two passes. In each pass, you want to ignore text nodes by default. In XSLT 1.0, you would write something like this:

<xsl:template match="text( )" mode="mode1"/>
<xsl:template match="text( )" mode="mode2"/>

In 2.0, however, you can avoid the redundancy:

<xsl:template match="text( )" mode="mode1 mode2"/>

Or, if you intend to filter in every mode:

<xsl:template match="text( )" mode="#all"/>

Admittedly, this is only a small improvement, but it pays off in more complex stylesheets, those using many modes, those whose modes share much code, or those frequently edited.

Discussion

One rule of thumb I follow when using modes in 2.0 is always to use #current instead of an explicitly named mode when I intend to continue processing in the current mode:

<xsl:template match="author" mode="index">
  <div class="author">
    <xsl:apply-templates mode="#current"/>
  </div>
</xsl:template>

This has two immediate benefits. First, if you later decide that the mode’s name was poorly chosen and want to change it, you do not have to change every call to xsl:apply-templates. Second, if you later extend the template with new modes, it continues to work without further changes:

<xsl:template match="author" mode="index body">
  <div class="author">
    <xsl:apply-templates mode="#current"/>
  </div>
</xsl:template>

  

 

 

 

back to top