How to create zebra-stripe CSS with TAL?

3.2k views Asked by At

How can I use Chameleon or Zope Page Templates to easily create CSS zebra striping? I want to add odd and even classes to each row in a table, but using a condition with repeat/name/odd or repeat/name/even looks rather verbose even with a conditional expression:

<table>
   <tr tal:repeat="row rows" 
       tal:attributes="class python:repeat['row'].odd and 'odd' or 'even'">
       <td tal:repeat="col row" tal:content="col">column text text</td>
   </tr>
</table>

This gets especially tedious if you have multiple classes to calculate.

1

There are 1 answers

0
Martijn Pieters On BEST ANSWER

The Zope Page Templates implementation for the repeat variable has an under-documented extra parameter, parity, than gives you the string 'odd' or 'even', alternating between iterations:

<table>
   <tr tal:repeat="row rows" 
       tal:attributes="class repeat/row/parity">
       <td tal:repeat="col row" tal:content="col">column text text</td>
   </tr>
</table>

This is also much easier to interpolate into a string expression:

tal:attributes="class string:striped ${row/class} ${repeat/row/parity}"

This works in Chameleon as well.