How to create zebra-stripe CSS with TAL?
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.
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.