4
votes

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 %}
4
Have you tried a simple if image.type == 'testtype'? - SirDerpington
Do you want to iterate over all company objects or just the ones with image.type "testtype"? If you want to iterate over all objects and just do a special output for the testtype images you could put the if in your for loop. {% if image.type == 'testtype' %} should work - SirDerpington
i just want to iterate over one object which has the property type = 'givenstring' - user2485214
Why do you pass all objects to your view if you just want one single object? - SirDerpington
the reason is that i have a company which contains three pictures.. top, middle and bottom picture.. which i defined with types.. now i need in the top position the top picture in the middle the middle one and so on...i dont wanted to save the pictures in the company table thats the reason why i have oneToMany here - user2485214

4 Answers

12
votes

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

6
votes

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

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

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

did you try this

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