Tuesday, February 1, 2022

[FIXED] Twig3: How to migrate "for item in items if item.foo == 'bar'" with loop bariable

Issue

I use the following Twig 2 code:

{% for item in items if item.foo == 'bar' %}
   <span class="{% if loop.index % 2 %}special-class{% endif %}">
       {{ item.value }}
   </span>
{% else %}
    Nothing found
{% endfor %}

In the twig docs: https://twig.symfony.com/doc/2.x/deprecated.html

Adding an if condition on a for tag is deprecated in Twig 2.10. Use a filter filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop)

I wonder how I migrate my Twig 2 code to Twig 3. As you see I use the loop variable and else in the for loop. I know that I can use a new parameter and increase it myself... but it that really the intention? How do I rewrite this code using filter?


Solution

Using the filter filter your code would look something like this (see also https://twigfiddle.com/9hiayc and https://twigfiddle.com/9hiayc/2):

{% for item in items|filter(i => i.foo == 'bar') %}
   <span class="{% if loop.index % 2 %}special-class{% endif %}">
       {{ item.value }}
   </span>
{% else %}
    Nothing found
{% endfor %}


Answered By - xabbuh

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.