caucho
 XSL Modes


XSL modes are an advanced XSL feature. Some pages need to evaluate the same XML twice. For example, a table of contents needs to create lists of the section titles, but the "normal" printing needs to output the section contents.

XSL adds modes to process XML elements in different ways. If the stylesheet specifies the mode attribute in xsl:apply-templates, the XSL engine will only match templates with the matching mode.

The following example has two modes: the default mode and a "summary" mode. The summary mode is used to generate a table of contents. The <summary/> tag creates the table of contents. It calls xsl:apply-templates with the summary mode. The only template in summary mode is a section template. It will add items to the table of contents.

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

<xsl:template match="section" mode="summary">
  <li><xsl:value-of select="@title"/>
  <xsl:if test="section">
    <ol><xsl:apply-templates mode="summary"/></ol>
  </xsl:if>
</li>
</xsl:template>

<xsl:template match="summary">
<ol>
  <xsl:apply-templates select="../section" mode="summary"/>
</ol>
</xsl:template>

<template match="section">
</template>

</xsl:stylesheet>

To simplify the example, the template for <section> does nothing. So only the summary will be generated from the XTP file.

hello.xtp
<summary/>

<section title="First Section">
Some text

<section title="Subsection A">
Subtext
</section>

<section title="Subsection B">
Subtext
</section>
</section>

<section title="Second Section">
Draft text
</section>

<ol>
  <li>First Section
  <ol>
    <li>Subsection A</li>
    <li>Subsection B</li>
  </ol>
  </li>
  <li>Second Section</li>
</ol>

Strict XSL

The StyleScript equivalent shows how to add arbitrary attributes in a StyleScript function. foo=>bar will set the value bar to the attribute foo.

default.xsl
$template(section, mode=>summary) <<
<li>$(@title)
  $if (section) <<
    <ol>$apply-templates(mode=>summary);</ol>
  >>
</li>
>>

$template(summary) <<
<ol>
  $apply-templates(../section, mode=>summary);
</ol>
>>

$template(section) <<
>>

Summary

  • modes let stylesheets extract new formats from the same XML.
  • name=>value specifies named attributes in XTP.
  • $if conditionally evaluates part of a stylesheet.
  • The XPath pattern ../a selects all the siblings of a.

Copyright © 1998-2002 Caucho Technology, Inc. All rights reserved.
Resin® is a registered trademark, and HardCoretm and Quercustm are trademarks of Caucho Technology, Inc.