# Recursive loops

Recursive loops are a powerful means of building a hierarchical display. The programming code required is particularly simple, but to use this recursive function you need to have a clear understanding of the sequence of the loops involved.

It’s easy to call a recursive loop: instead of the TYPE of the outer loop, you simply indicate the name of another loop:

<BOUCLEx …>
…
<BOUCLEn(BOUCLEx)></BOUCLEn>
…
</BOUCLEx>


The n loop works as if the entire x loop (all tags and HTML code, as well as conditional text before, after and alternative) had been copied to the place where the n loop is inserted.
As the n loop is inside the x loop, this results in recursive behaviour: the x loop contains a n loop, which in turn reproduces the x loop, which contains the n loop, and so on, until the x loop gives no more results.
There are no criteria in the loop n, as the change of context at each call of the loop x should lead the criteria of the loop x to find no more elements.

One useful application of this technique is to display the threads of the forums. It provides this problem with a very simple solution: a first loop catches the beginning of the threads (the forum messages which reply directly to an article), then a second loop shows the feedback to these messages, and finally a recursive loop generates a recursiveness of this second loop:

<BOUCLE_forum(FORUMS){id_article}>
#TITRE
<B_feedback>
<ul>
<BOUCLE_feedback(FORUMS){id_parent}>
<li>#TITRE
<BOUCLE_recursive(boucle_feedback)>
</BOUCLE_recursive>
</li>
</BOUCLE_feedback>
</ul>
</B_feedback>
</BOUCLE_forum>


In a similar way it is also possible, using only a few lines of code, to display the whole structure (sections, sub-sections, etc.) of the site.

Comment 1 : The compiler considers the notation BOUCLEn(BOUCLEx)> outside the loop x to be meaningless, which allows it to achieve optimality in the number of fields in the SQL queries it produces, for any type of loop.
This use is not a recursion but an inclusion, a feature met by the much preferable INCLURE tag.

Comment 2 : In the current state of the SPIP compiler, the sequence <BOUCLEn(BOUCLEx)></BOUCLEn> must be at the first level of the x loop, i.e. the n loop must be immediately encompassed by the x loop, not by another loop itself inside the x loop.
The removal of this restriction is under consideration.

Comment 3 : You can call a tag which is the namesake of one of the enclosing loops by specifying the name of the loop to which the tag belongs. The name of the loop must then be specified between the # and the tag name. More details in the article SPIP’s tags: the syntax.

We would then write the loop tag #TAG of the loop _loop [1] as follows:
#_loop:TAG.

Author Published : Updated : 20/04/23

Translations : عربي, català, Deutsch, English, Español, français, italiano, Nederlands