Skip to main content

Working in Laravel, I needed to loop through an array and know whether the current loop was odd or even row.  To do this add the expression to your Twig file:

{% set direction = loop.index0 is odd ? 'left' : 'right' %}

In the call above, the variable direction is set to either left or right depending on the value of the position of the loop row (loop.index0).  I then used the left or right value in a div class adding to a series of tailwind css definitions.  Such as text-{{ direction }}

The full div tag in this instance was:

<div class="font-light block text-5xl py-5 px-10 text-{{ direction }} tracking-wider text-white">{{ item.title }}</div>

The expression odd returns true if the given number is odd:

{{ var is odd }}

Therefore in the set direction call above, when odd is true the value of direction will be left.

 

Other twig set calls
{% set foo = 'bar' %}

After the set call, the foo variable is available in the template like any other ones:

{# displays bar #}

{{ foo }}

The assigned value can be any valid Twig expression:

{% set foo = [1, 2] %}

{% set foo = {'foo': 'bar'} %}

{% set foo = 'foo' ~ 'bar' %}

Several variables can be assigned in one block:

{% set foo, bar = 'foo', 'bar' %}

The above call is equivalent to writing:

{% set foo = 'foo' %}

{% set bar = 'bar' %}

The set tag can also be used to ‘capture’ chunks of text:

{% set foo %}
    <div id="pagination">
        ...
    </div>
{% endset %}

If you enable automatic output escaping, Twig will only consider the content to be safe when capturing chunks of text.

Note, that loops are scoped in Twig; therefore a variable declared inside a for loop is not accessible outside the loop itself:

{% for item in list %}
    {% set foo = item %}
{% endfor %}

{# foo is NOT available #}

If you want to access the variable, just declare it before the loop:

{% set foo = "" %}
{% for item in list %}
    {% set foo = item %}
{% endfor %}

{# foo is available #}