Marc
Marc

Reputation: 9527

TWIG - How to display item with specific attribute without looping

I use a loop to display an image that has its attribute 'place' equal to 2. So I do the following.

{% for image in entity.images %}
   {% if image.place == 2 %}
       ...                                          
   {% endif %}
{% endfor %}

That is a quite consuming process. So what I would like is to be abble to identify the item straight ahead. For example to get the image that has its attribute 'place' equal to 2, I would love to have something like {{ entity.images|image.place[2] }}. Unfortunately this is not working. Hope someone can help. Thank you in advance. Cheers. Marc

Upvotes: 0

Views: 1161

Answers (1)

Ahmed Siouani
Ahmed Siouani

Reputation: 13891

No, there's no silver bullet to do such thing, even if you want to add a getImageByFilter() method to your entity, you'll need to iterate through the collection of images to get the right one.

Same for using a twig helper (which I don't recommend).

Keep in mind that if you're trying to get a given entity from a collection that's related to your main entity, you need to go through the collection to look for the one that fits your constraint.

Update,

Also, take a look at Adding a condition example of the twig for loop documentation that may probably help you skip iterating through the entire collection.

As explained in this Github Twig Repository issue, it's not possible to break or continue in a loop.

From the documentation,

Unlike in PHP, it's not possible to break or continue in a loop. You can however filter the sequence during iteration which allows you to skip items. The following example skips all the users which are not active:

<ul>
    {% for element in entity.elements if element.isOk %}
        <li>{{ element.attribute }}</li>
    {% endfor %}
</ul>

The advantage is that the special loop variable will count correctly thus not counting the users not iterated over. Keep in mind that properties like loop.last will not be defined when using loop conditions.

Upvotes: 2

Related Questions