Monday, 14 January 2008

Creating Simple Loops in XSLT

Here's a simple way to create a loop in XSLT. As you might expect, it uses recursion.

I have defined a template that will do the work of the loop. It checks the value of a variable called 'counter' before calling itself. This is the loop condition. Before this test, you can add whatever it is you need the loop to do. In the following example, I print the letters of the alphabet, followed by "... Hello!":

<xsl:template name="DoLoop">
<xsl:param name="counter" />
<xsl:variable name="letter"
select="substring($alphabet, $counter, 1)" />

<!--Body of loop goes here-->

<xsl:value-of select="$letter" />... Hello!

<!--End of loop body-->

<xsl:if test="$counter &lt; 26">
<xsl:call-template name="DoLoop">
<xsl:with-param name="counter">
<xsl:value-of select="$counter+1" />

The loop is then initiated by calling it with the desired starting value:

<xsl:call-template name="DoLoop">
<xsl:with-param name="counter">1</xsl:with-param>

For info, the alphabet variable is simply defined as:

<xsl:variable name="alphabet">


NielsR said...

Thanks, just what I needed.
Sad there's no for loop and that we have to use recursion (to keep it simple :D). But I can understand because XSL is based on transformation but sometimes a for comes in handy. To say it with the words of Dijkstra "Two or more, use a for" :).

Martin Vestergaard Nielsen said...

Great work. Was just looking for an easy XSLT snippet to make a list of letters.

Thanks for sharing :)