Using The Cycle Function In Twig

I was looking at adding zebra stripes to some data to improve readability to a page of data generated from PHP using the Twig templating system.

Twig provides a method called cycle that can be used to alternate through a list of values, so this is was the obvious candidate.

cycle takes 2 parameters, the first is an array of values to iterate through, the second is an integer with the cycle value.

This means all I have to do is to pass in an array with the css class names I’m using for my striping, and the position of the loop I’m iterating through to display my data. For example…

{% if users|length > 0 %}
{% for user in users %}
  <li class="{{ cycle(['even','odd'],loop.index) }}">{{ user.username|e }}</li>
{% endfor %}
{% endif %}

I have a list of users that I’m iterating through. For each user I choose wether to display use either the odd or even class using the cycle function. I have to pass in loop.index as the cycle value to count as this increments each time the loop is iterated through.

This gave me an output something like this…

  <li class="even">Rob</li>
  <li class="odd">John</li>
  <li class="even">Paul</li>
  <li class="odd">George</li>
  <li class="even">Ringo</li>

2 thoughts on “Using The Cycle Function In Twig”

  1. This is not 100% correct. In your example the circle would start with odd cause loop.index starts with the second index. If you really want to start with the first index use index.loop0

Comments are closed.