Skip to content

Instantly share code, notes, and snippets.

@jpetitcolas
Created January 8, 2013 06:29
Show Gist options
  • Save jpetitcolas/4481722 to your computer and use it in GitHub Desktop.
Save jpetitcolas/4481722 to your computer and use it in GitHub Desktop.
How to differenciate odd and even rows with Twig?
<table>
{% for record in records %}
<tr class="record{% if loop.index is divisibleby(2) %}even{% else %}odd{% endif %}">
<td>{{ record.id }}</td>
<td>{{ record.title }}</td>
</tr>
{% endfor %}
</table>
@mCzolko
Copy link

mCzolko commented Jun 20, 2016

@robandwend
Copy link

or use the twig cycle function

{% for year in start_year..end_year %}
{{ cycle(['odd', 'even'], loop.index0) }}
{% endfor %}

@sonyarianto
Copy link

divisibleby(2) should be divisible by(2)

@jameswilson
Copy link

jameswilson commented Apr 2, 2020

{% if loop.index is divisibleby(2) %}even{% else %}odd{% endif %} could be shortened to
{{ loop.index0 is odd ? 'odd' : 'even' }}

@marlisa31
Copy link

this works too:

{% if loop.index is even %} ... {% else %} ... {% endif %}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment