Alternate css classes easily in twig

Saturday, February 2, 2013

twig

Today, I wanted to style a little bit my project. The basic way in classic PHP project would be to use the iterator variable of your for loop with the use of modulo.

For example:

    {% raw %}<div class="<?php echo ($i % 2 == 0) 'odd' : 'even' ; ?>"></div>{% endraw %}

In twig, when you use a loop, there are several variables that you can use like loop.index, loop.first, loop.last. I won’t copy/paste the official documentation here, you can read it here twig loop documentation.

To use the modulo function in twig, just use

    {% raw %} {{ 10 % 2 }} {% endraw %}

And there you go, as simple as in PHP.

Then, using twig, you can do this:


    {% raw %} {% if loop.index % 2 == 0 %} {% endraw %}

Or in my case I needed this :


    {% raw %} {% if loop.parent.loop.index % 2 == 0 %} {% endraw %}

To be able to use the index of my parent loop :)

On this blog, I found the following tips :


    {% raw %} {% if loop.index divisibleby(2) %} {% endraw %}

Isn’t it beautiful ? But it gets even better!


    {% raw %} {{ cycle(['odd', 'even'], loop.index) }} {% endraw %}

And there you go, thank you twig !


Contact

If you find any issue or have any question about this article, feel free to reach out to me via email, mastodon or even IRC, see the About Me page for details.

Saving a vim session before quitting

Switching quickly from 1 screen to 2