Coding with SPIP 3.0
SPIP3.0 Technical Documentation

> > > > Recursive loops

Recursive loops

A common concept in many programming languages, an algorithm (a data-processing code) which makes reference calls to itself is described as being "recursive". Here, a recursive loop (n), contained in a parent loop (x), makes it possible to execute the loop (x) again, by automatically passing it the required arguments. Therefore, inside the loop (x), the same loop (x) is called with different parameters. This is what we refer to as recursion. This process will be repeated as many times as the recursive loop returns results.

  1. <BOUCLEx(TABLE){id_parent}>
  2. ...
  3. <BOUCLEn(BOUCLEx) />
  4. ...
  5. </BOUCLEx>

Download

When a site has many sub-sections, or many forum messages, it often uses recursive loops. This makes it possible to display identical elements very easily.

Example

We can use a recursive loop to display a list of all of the sections in the site. To do so, we loop for the first time on the sections, with a criterion that selects the sub-sections of the current section:
{id_parent}. We also sort by numbers (assigned to the sections so that we can display them in a particular order), and then by titles (in case the numbers are absent or repeated for sections within a given parent section).

  1. <B_rubs>
  2. <ul>
  3. <BOUCLE_rubs(RUBRIQUES){id_parent}{par num titre, titre}>
  4. <li>#TITRE
  5. <BOUCLE_sous_rubs(BOUCLE_rubs) />
  6. </li>
  7. </BOUCLE_rubs>
  8. </ul>
  9. </B_rubs>

Download

In the first iteration of the loop, {id_parent} will list the sections at the root of the site. These "root" sections all have an id_parent field equal to zero. When the first section is displayed, the recursive loop is called and so SPIP calls the loop “_rubs” again. This time the {id_parent} criterion selects a different set of sections because it will list the sub-sections of the current section. If there are sub-sections, the first one is displayed. Then the “_rubs” loop is called again, but now for this sub-section. As long as there are deeper sub-sections to display, this recursive process will repeat.

Result:

  1. <ul>
  2. <li>en
  3. <ul>
  4. <li>Introduction</li>
  5. <li>The templates
  6. <ul>
  7. <li>Loops</li>
  8. </ul>
  9. </li>
  10. <li>Extending SPIP
  11. <ul>
  12. <li>Introduction</li>
  13. <li>Pipelines</li>
  14. ...
  15. </ul>
  16. </li>
  17. ...
  18. </ul>
  19. </li>
  20. <li>fr
  21. <ul>
  22. <li>Introduction</li>
  23. <li>Template syntax
  24. <ul>
  25. <li>Loops</li>
  26. <li>Tags</li>
  27. <li>Loops criteria</li>
  28. ...
  29. </ul>
  30. </li>
  31. ...
  32. </ul>
  33. </li>
  34. </ul>

Download

  • More

    Understanding the principals of recursive programming is not easy. If this explanation has left you confused, you may find it helpful to read the article about recursive loops on SPIP.net:
    http://www.spip.net/en_article2090.html