34

Hello i would like do somthing like that:

<?php $count = 0; foreach($a as $v): $count++; ?>
  <?php if ($count%2 == 0): ?>
    ...
  <?php endif; ?>
<?php endforeach; ?>

in twig:

{% for v in a %} 
  {% if ??? is even %}
    ...
  {% endif %}
{% endfor %}

but how can i have a variable evolving with loop ?

2 Answers 2

66

Apparently twig defines some loop variables inside the for-loop:

{% for v in a %}
    {% if loop.index0 is even %}
        ...
    {% endif %}
{% endfor %}
Sign up to request clarification or add additional context in comments.

3 Comments

There is also such a thing as {% if loop.index is divisible by(2) %}, which would do the same. twig.symfony.com/doc/2.x/tests/divisibleby.html
The link in the answer has expired. Use this one instead: twig.symfony.com/doc/3.x/tags/for.html#the-loop-variable
@Charles hey thank you very much for the message, I have updated my answer accordingly.
24

If you use it for styling you can do:

{% for v in a %} 
  <div class="link {{ cycle(['even', 'odd'], loop.index0) }}">
  </div>
{% endfor %}

2 Comments

Thanks, exactly what I was looking for. However, just a minor fix: It should be cycle(['even', 'odd'], loop.index0) because loop.index0 is used. When you use loop.index0 you are saying you have a "zeroth" row, and zero is an even number. So, with this fix your zeroth row is even, first row is odd, second row is even, etc.
Pretty neat solution, especially if you need something different than "even and odd", but for example "1st, 2nd and 3rd". Now, what about performance? Is maybe using {% if loop.index0 is even %} faster than cycling through a list of strings with {{ cycle(['even', 'odd'], loop.index0) }}? Would be interesting to know if there might be any reason to prefer one solution over the other or if it just doesn't matter in the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.