RE: [xsl] When/How to use templates, and when to use if/choose

Subject: RE: [xsl] When/How to use templates, and when to use if/choose
From: "Michael Kay" <mike@xxxxxxxxxxxx>
Date: Tue, 19 Jun 2007 23:55:22 +0100
> Using templates sometimes seems to be more of a pain than not!

Well, this first example certainly seems to read much better with templates:

<xsl:template match="doc:Body//doc:Para">
  <xsl:number count="doc:Para" from="doc:Body" level="any"/>
  <xsl:text>. </xsl:text>
  <xsl:call-template name="prefix"/>

<xsl:template match="doc:appendix//doc:Para">
  <font xsl:use-attribute-sets="attSetAppendixBody">
    <xsl:call-template name="prefix"/>

<xsl:template match="doc:Para">
  <xsl:call-template name="prefix"/>

What are the benefits? Well, it's a bit shorter, and it's a bit more
readable, but the main benefit is reusability of code and potential for
change. An importing stylesheet can override any one of these templates
without being concerned with the others, or it can add extra templates that
select a different subset of the doc:Para elements. As soon as you want to
create a suite of stylesheets that do a number of different jobs, or process
a variety of different inputs, that becomes invaluable.

> Also,
> <xsl:template match="doc:title">
>     <xsl:choose>
>         <xsl:when test="parent::doc:Table">
>             <xsl:apply-templates/>
>         </xsl:when>
>         <xsl:when test="ancestor::doc:Summary">
>             <xsl:choose>
>                 <xsl:when test="../../../../doc:Section">

This is starting to look pretty hideous; it certainly feels to me that rules
of the form

<xsl:template match="doc:Section//doc:Summary/doc:Table/doc:title">

are vastly preferable. But you don't have to do everything with templates:
looking at the above, without knowing anything about your problem, I would
probably be inclined to process most of the title elements from their
containing element, for example

<xsl:template match="doc:Table">
  <p><xsl:value-of select="doc:title"></p>

rather than having a rule for titles that worries about all the possible
places they can appear.

Michael Kay

Current Thread