Re: Functions or templates? My rules of thumb

You’re right, I should have said “have to be invoked by <xsl:call-template> or <xsl:apply-templates>”. My rule of thumb is to use templates whenever the result is a sequence of newly generated nodes. I use matching templates when I can (when the output largely depends on a single node) and named templates when I have to (when I have to recurse or when there isn’t a parameter that’s a single node).

For example, I would do

<xsl:template name="makeEmptyCells" as="element(td)*">
  <xsl:param name="n" as="xs:integer" />
  <xsl:for-each select="1 to $n">
    <td>&#xA0;</td>
  </xsl:for-each>
</xsl:template>

rather than

<xsl:function name="eg:makeEmptyCells" as="element(td)*">
  <xsl:param name="n" as="xs:integer" />
  <xsl:for-each select="1 to $n">
    <td>&#xA0;</td>
  </xsl:for-each>
</xsl:function>

mostly because doing

<tr>
  <xsl:apply-templates select="$cells" />
  <xsl:sequence select="eg:makeEmptyCells(5 - count($cells))" />
</tr>

doesn’t feel right. (I struggle to rationalise this gut feeling.)

So I still use named templates, even in XSLT 2.0.

Reply

The content of this field is kept private and will not be shown publicly.