[ar] [ast] [bg] [br] [ca] [co] [cpf] [cs] [da] [de] [en] [eo] [es] [eu] [fa] [fon] [fr] [gl] [id] [it] [ja] [lb] [nl] [oc] [pl] [pt] [ro] [ru] [sk] [sv] [tr] [uk] [vi] [zh] Espace de traduction

Download

Recursive loops

October 2003 — updated on : April 2005

All the versions of this article:


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:

There is no criterion involved. In fact, loop n is simply a copy of loop x. The whole structure functions exactly as if you had copied the whole of loop x, with all its contents (the Spip and HTML tags, the text, as well as the conditional texts – before, after and alternative), at the location where you insert loop n. (Loop x must, of course, have been previously declared.)

So the simplest use of this structure is to "duplicate" a loop without having to re-write it, with the added advantage that any change made to the x source loop will be automatically reflected in loop n.

However, the whole value of this syntax lies in also including loop n within loop x. This gives a recursive action: loop x contains another loop, n, which itself triggers loop x containing loop n and so on, until loop x runs out of results.

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:

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.


Show the template of this page Site powered by SPIP | Translation area | Private area