31
votes

I try to do zebra striping:

{% set counter = 0 %}
{% for entity in entities %}
  <tr class="{{ cycle(['odd', 'even'], counter) }}">
    {% counter++ %}

but I am getting error:

Unexpected tag name "counter" (expecting closing tag for the "for" tag defined near line 11)

Could somebody give me solution?

[EDIT]

My bad solution is so easy:

{% set counter = counter + 1 %}
2
Is this for a table? <table class="table tabled-striped"> - zkent

2 Answers

37
votes

There's an easier way to do what you want:

{{ cycle(["even", "odd"], loop.index) }}

See the docs for the loop goodies.

5
votes

If you want to have full control over the html, you can try this:

{% if loop.index is divisibleby(2) %}
    ...
{% endif %}

You can read it here: http://twig.sensiolabs.org/doc/tests/divisibleby.html

note that loop.index is used 'as-is', it does not refer to a variable rather the hidden indexing of the for loop.