Ivan Buttinoni
Ivan Buttinoni

Reputation: 4145

How can apply a "filter filter" in a for instead using an "if" in 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?

Upvotes: 4

Views: 1191

Answers (1)

Edi Modrić
Edi Modrić

Reputation: 2310

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>

Upvotes: 4

Related Questions