Score:3

Looping through child elements in Twig 2.10 without using if

na flag

Currently I need to loop through child elements in my Twig to render dynamic grids properly. I have achieved this by using code similar to this

{% for key, child in element if key|first != '#' %}
  <div>{{ child }}</div>
{% endfor %}

This works exactly how I am needing it to work. However in Twig 2.10 using an if inside of a for is now deprecated and it is now recommended to use either a filter filter or an if inside the body of the for.

Using an "if" condition on "for" tag in "main.twig" at line 1 is deprecated since Twig 2.10.0, use a "filter" filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop).

I have been unable to figure out how to achieve the same effect using the filter filter in this case and could use some help with the change. I'm sure I'm making some basic error but my brain isn't solving this one quickly.

leymannx avatar
ne flag
The error message says it all already. Use just the for loop. And inside it use the standalone if condition. Not for-if, endfor but for, if, your markup, endif, endfor. That's all.
Lurnobis avatar
na flag
I did try this and it worked for most things, however with how some of my custom blocks are set up it would end up throwing errors so I wasn't sure if there were other options.
Score:5
in flag

You can install the Twig Tweak module and use the children filter it provides.

For example:

{% for child in element|children %}
  <div>{{ child }}</div>
{% endfor %}
Lurnobis avatar
na flag
Wow that made my life fantastically better and drastically simpler. Thanks sonfd.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.