XSLT named templates

Named Templates

1. Passing Variables to a called template
2. xsl:template having both name and match

1.

Passing Variables to a called template

Mike Brown

Updated from the vellum orginal (DaveP).

To pass a variable to a called
template, you need to use with-param and param , like this:

<xsl:template match="/">
    <xsl:variable name="DebugOpts" select="abc123"/>
    <xsl:call-template name="childTemplate">
        <xsl:with-param name="DebugOpts" select="$DebugOpts"/>
    </xsl:call-template>
</xsl:template>

<xsl:template name="childTemplate">
    <xsl:param="DebugOpts" select="."/>
    <xsl:text>The value of $DebugOpts is: </xsl:text>
    <xsl:value-of select="$DebugOpts"/>
</xsl:template>

This technique can be used to pass parameters back and forth between
templates. An increment function could be simulated this way.
            

2.

xsl:template having both name and match

Colin Paul Adams, David Carlisle


    > This means that we can write a xsl:template having *both*
    > name and match attributes..

    > I want to know in which circumstances such a template
    > definition is useful.. Can somebody please provide an
    > example where this has real practical use..?

This is used extensively in FXSL for XSLT2.

Where a test does not require any source document, then the initial template is defined like:

<xsl:template match="/" name="initial"> etc.

Then you can invoke the test from the command line, without having to supply a source XML document.

But if this is not convenient, so the match ="/" is retained for this purpose.

DC adds

I use it sometimes. suppose you have two elements in your source <foo>xxx</foo> and <bar>xxx</bar> and you want foo to generate the same output as bar except that it has to be surrounded by <div class="foo"> ...</div>.

One way is to have

<xsl:template match="bar" name="bar">
 <span><xsl:apply-templates/></span>
</xsl:template>
<xsl:template match="foo">
 <div class="foo"><xsl:call-template name="bar"/></div> </xsl:template>

Of course, there are other ways to achieve this, but still this idiom comes in handy sometimes.

Dave Tucker offers

I use this capability to write templates where the first invocation comes from matching some source element, and subsequent invocations are from recursive calls. For example:

  <xsl:template match="insert-events" name="insert-events">
    <xsl:param name="days-from-now">0</xsl:param>

    <xsl:if test="$days-from-now &lt; 7">
      <!-- process this day -->
      <!-- ... -->

      <!-- recursively call insert-event for next day -->
      <xsl:call-template name="insert-events">
        <xsl:with-param name="days-from-now" select="$days-from-now + 1"/>
      </xsl:call-template>
    </xsl:if>
  </xsl:template>

Notice that this pattern also relies on having default parameter values.