user2485214
user2485214

Reputation: 227

if condition in for loop in twig template engine

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 %}

Upvotes: 8

Views: 32372

Answers (4)

Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46188

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 %}

Upvotes: 23

Tomas Tibensky
Tomas Tibensky

Reputation: 821

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

Upvotes: 12

paidforbychrist
paidforbychrist

Reputation: 359

As long as testtype is a string, then I would try:

{% for image in company.images if image.type == 'testtype' %}

Upvotes: 1

Mohamed A
Mohamed A

Reputation: 71

did you try this

{% for myimage in company.images %}
   {% if myimage.type == 'testtype' %}
   {% endif %}
{% endfor %}

Upvotes: 5

Related Questions