Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if condition in for loop in twig template engine

Tags:

twig

symfony

Every company object is with a one-to-many relation with image.
Now in my template I want to check if there is an image of type testtype.

How to handle this with twig? The following gives me an exception:

Unexpected token "string" of value "testtype" ("name" expected)

Twig

{% for image in company.images if image.type is 'testtype' %}
{% endfor %}
like image 582
user2485214 Avatar asked Nov 29 '22 01:11

user2485214


2 Answers

The new way to do that is the following (for if is deprecated since Twig 2.10):

{% for image in company.images|filter(image => image.type is 'testtype') %}
{% endfor %}
like image 103
Pierre de LESPINAY Avatar answered Dec 29 '22 03:12

Pierre de LESPINAY


warning: this answer is already deprecated

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

http://twig.sensiolabs.org/doc/tags/for.html#adding-a-condition

like image 34
Tomáš Tibenský Avatar answered Dec 29 '22 04:12

Tomáš Tibenský