Displaying elements as rows in a table

For example, you want to create a table containing the titles of a section’s articles arranged in three columns, the number of lines depending on the total number of articles, like this:

article 1 article 2 article 3
article 4 article 5 article 6
article 7 article 8 article 9

It is, of course, necessary to use an ARTICLE loop, but the difficult lies in inserting the opening and closing tr tags for every time the loop repeats a third time. The trick lies in using the #COMPTEUR_BOUCLE tag and the alterner filter. The tag tells us how many times we have been through the loop already: if its remainder after division by 3 equals 0, then we need to create an opening tr tag at the start of the code, and if it equals 2,then we must generate a closing tr tag at the end instead.

To do this, there’s no need to actually do such arithmetic calculations inside of the squelette template code. We need only use the alterner filter, which accepts any number of arguments, which we will call n, the first being an integer which we will call i. Our filter calculates the remainder k of the division of n-1 by i and then returns its k+th argument as a result. All that is then needed is to give it 3 empty arguments, excepting one in the right spot so that it produces the tr tags in the right places.

If we wish to generate completely correct HTML code, we must generate a sequence of <td></td> after the loop to complete the last line of the table when the total number of articles is not divisible by 3. Once again, we only need to use the alterner filter, but applied this time to the #TOTAL_BOUCLE tag.

Altogether we then have:

To improve legibility of the resulting HTML table, we can colour the odd and even lines differently by assigning a style attribute into the opening tr tag. We must therefore replace the '<tr>' in the code above by a new application of #COMPTEUR_BOUCLE|alterner, the argument of a filter by able itself to make use of tags and filters. The following template code will then generate the table as furst seen at the top of this article:

The same type of loop, but replacing the call to the title with one for the logo (using the #LOGO_ARTICLE tag), allows you to display a gallery where each article logo provides a preview image (the size of which will be preferably predetermined so that the page can be formatted nicely), and the text of the article contains the contain images shone as thumbnails.

To achieve these results, the initial version of this article used recursive loops in an innovative manner. Doing so will not always be possible in SPIP, and is additionally a less efficient method than the one shown above to replace it, most especially because it only requires a single SQL query to be executed on the host database server.

Author Mark, Paul Knight Published : Updated : 26/10/12

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