Alternating Table Rows With Template Toolkit And CSS

Whilst looking at a potential recode of the Smash Hits Chart website, I came across the need to make each alternate row in the main chart table a different colour.

As the recode will be using Template Toolkit, this is simple.

The chart is passed as a list, so we have to iterate over it to get each entry out. I do this using a simple [% FOREACH %]. Template Toolkit thoughtfully provides us with a Template::Iterator object called loop inside the FOREACH block, so we can use the index() method to get the current elements list position. Using this, we just need to check if the value is odd or even to decide what colour to make the row.

Let’s see some sample code. To change the row’s colour I’m going to use two CSS classes called lite and dark.

[% FOREACH entry = chart %]
<tr class="[% IF loop.index % 2 %]lite[% ELSE %]dark[% END %]">
<td>[% entry.position %]</td>
<td>[% entry.artist %]</td>
<td>[% entry.track %]</td>
[% END %]

The magic is in the line loop.index % 2. It takes the remainer (modulus) of loop.index divided by 2. This returns either 0 or 1, which is what Template Toolkit uses to determine truth, so can be used directly in the IF statement.