Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can apply a "filter filter" in a for instead using an "if" in Twig

Tags:

twig

From the deprecated page of Twig documentation:

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)

If it's clear to me the part:

an "if" condition inside the "for" body

In this way:

<ul>
    {% for user in users if user.active %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>

Instead this part it's not clear:

Use a filter filter

Any example explaining how doing it wrong and doing it right?

like image 664
Ivan Buttinoni Avatar asked Sep 15 '25 11:09

Ivan Buttinoni


1 Answers

It should be this way (taken from the docs):

<ul>
    {% for user in users|filter(user => user.active) %}
        <li>{{ user.username|e }}</li>
    {% endfor %}
</ul>
like image 150
Edi Modrić Avatar answered Sep 17 '25 08:09

Edi Modrić