XSLT - Recursion

There are a couple of things that make XSLT hard to manage and recursion is indeed one of them. There is just no way of running a traditional for loop. In order to solve this we need either a structure to iterate on, or we can create a template that calls itself with a counter and control number.

If you simply need to iterate on an XML structure, you can do a for-each loop like this:

  1. <xsl:for-each select=".//child::title">
  2. <!-- Do you thing-->
  3. </ xsl:for-each >

However, if you know that you need to iterate on a procedure "i" times, then we need to complicate things a bit.

  1. <xsl:template name="test3">
  2. <xsl:param name="counter"/>
  3. <xsl:param name="i"/>
  4.  
  5. <!--We do our thing...-->
  6. <xsl:copy>
  7. <xsl:text>Hello Nerd!</xsl:text>
  8. </xsl:copy>
  9. <xsl:if test="$i &gt; $counter">
  10. <xsl:call-template name="test3">
  11. <xsl:with-param name="counter" select="$counter+1"/>
  12. <xsl:with-param name="i" select="$i"/>
  13. </xsl:call-template>
  14. </xsl:if>
  15. </ xsl:template >

To call the template we need to provide it with the starting parameters:

  1. <xsl:call-template name="test3">
  2. <xsl:with-param name="counter">0</xsl:with-param>
  3. <xsl:with-param name="i">10</xsl:with-param>
  4. </ xsl:call-template >

Make sure that you take into consideration that the if test checks if the $i is still greater than the $counter variable. If you write greater or equal you will get 10 + 1 runs of the template. Also make sure that the call comes after you've done your magic in the loop. Otherwise you just won't get anything. The template executes line by line, so if you include any code after the template call, it will execute once(!) no matter how many iterations you initially ask for.

Comments

Popular posts from this blog

Designing and programming - Part 2

Filtering Dropdown choices in a Power Pages form using Dataverse Relations

Exploring the Power of Variables in Liquid and Power Pages