blog archive contact about feed

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.

<table> [% 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> <tr> [% END %] </table>

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.

Entered: 2004-09-13 16:09:48
Modified: 2009-03-19 11:46:52

Trackbacks

Altanierende Tabellenzeilen mit Template Toolkit by echox's blog
Bei langen Tabellen ist es fuer den Benutzer in der Regel angenehmer, wenn die Zeilen in leicht unterschiedlichen Farben gestaltet sind. Die richtige Stelle um fuer den Entwickler diese 'Funktion' in die Anwendung einzubauen sollte die Template Engine...

Tracked: 2007-12-14 15:58:45

Rob's Other Blog Entries

See other blog entries for September 2004, or an index of all blog entries.