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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.