Re: [xsl] xsl:function vs named templates (Which is better?)

Subject: Re: [xsl] xsl:function vs named templates (Which is better?)
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Wed, 14 Mar 2007 22:27:35 +0100
Jernigan, TieSha wrote:
So I have a fairly general question. I am using XSLT 2.0 and am
interested in creating user defined functions. Which construct is better
to use... xsl:function or a named template?

Indeed fairly general, but not easy to answer. The answer lies somewhere between your own taste, the places where you are about to use the function and what return type the function has. If you want to be able to use your function within XPath syntax, you *must* choose a function, and not a named template. For reasons of personal taste, I tend to use a function when it has to run recursively.


Other points you can balance are: A
- Are you writing a function library? Go for functions, they are easier to maintain.
- Do you have a need for predefined values for your parameters? Go for templates.
- Do you need tunneling variables? Then templates is your onely option.
- Is all you need to do manipulating some atomic value (i.e., string, integer, double, url etc), then using a template is overkill.
- Do you need the current execution context (i.e., do you want to act on the current selected node etc?)? Then your two options are: passing the node on to the function (bad idea) or use a named template, which won't loose the context.
- Do you like named parameters, for their ease of mnemonics? Use a named template with params


I want to replace it with .....

<greater>upperfreq</greater>
<lesser>lowerfreq</lesser>

You do not necessarily need a function for that. Just use plain template matching, like as follows:


<xsl:template match="greater">
   <xsl:text>upper</xsl:text>
   <xsl:value-of select="." />
</xsl:template>


Cheers, -- Abel Braaksma http://www.nuntia.nl

Current Thread