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…

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…

2 Responses to “Using The Cycle Function In Twig”

  1. Sören Martius

    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

    • Robert Price

      Or odd and even could just be swapped round in my original code.


Leave a Reply