2

I'm trying to display table rows with alternating colors. For that, I have two css classes row1 and row2 that I'd like to assign in an alternating pattern to the rows of a table. Ideally, I'd determine if the row is odd or even based on the forloop.counter variable

This is what I'd like the template to do (invalid code, but I think it's self explaning).

{% for norma in normas %}
{% if forloop.counter %2 != 0 %}
<tr class="row1">
{% else %}
<tr class="row2">
{% endif %}
    <td>yadda... yadda</td>
    .
    .
    .
{% endfor %}

Is there a way to do this within django template system?

dariopy
  • 568
  • 1
  • 7
  • 18
  • here is solution to your problem this post explains deeply how to get alternating row colors http://stackoverflow.com/questions/459161/alternate-row-coloring-in-django-template-with-more-than-one-set-of-rows – Mayank Mar 14 '12 at 09:10

3 Answers3

3

Use cycle - the example shows this exact purpose

JamesO
  • 25,178
  • 4
  • 40
  • 42
1

Just use in your {%for%} loop :

<tr class="{% cycle 'row1' 'row2' %}>

django templete will cycle through each row. you can add as many items in the cycle.

Nuno_147
  • 2,817
  • 5
  • 23
  • 36
1

the followin post explains how to get alternating row colors in Django.

Alternate Row Coloring in Django Template with More Than One Set of Rows

Community
  • 1
  • 1
Mayank
  • 8,777
  • 4
  • 35
  • 60