modulo in Twig

Ever wondered how to use the modulo operator in twig, the template engine of symfony?

Actually its like in PHP:

{{ 11 % 7 }}

As described here

But i guess for most use cases modulus is used to check if a number is divisible by another number.
Therefore Twig has the very conveniant divisible by test function.

{% if loop.index is divisible by(3) %}


Another modulo use case is to check odd and even rows in loops. There Twig has the built-in function cycle to help you.

{{ cycle(['odd', 'even'], i) }}

Once you know its so eeasy;)

5 Replies to “modulo in Twig”

  1. Pingback: - We are php
  2. You have a little syntax issue. Thank you for this very good post

    {% if key is divisible by(2) %}

    For me it now works in a symfony SULU CMS project.

Comments are closed.