Edgewall Software

Genshi Recipes: Alternating Table Row Styles

When working with a list of data you wish to display in a table it is nice to have alternating table row styles for every other row (odd/even) to help make the data more readable. This can be done by using the enumerate function of python, and then using the index value from the function to decide if the row is odd or even by getting the remainder after dividing by 2. If the remainder is 1, the row is odd, otherwise the remainder is zero and the row is even.

Using py:for to loop through the list you can do the following:

<tr py:for="i, (firstname, lastname) in enumerate(nameslist)" class="${i%2 and 'odd' or 'even'}">

This will produce a table row in the html output with the class="odd" or class="even" alternating on each row.

Using itertools.cycle

Pass itertools.cycle to your template and:

<table py:with="cls=cycle(('first', 'second', 'third'))">
  <tr py:for="firstname, lastname in nameslist" class="${cls.next()}">

This will produce table rows cycling through class="first", class="second" and class="third".

Last modified 10 years ago Last modified on Mar 2, 2008 7:49:37 AM