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.

  • 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.
    – leymannx
    Jan 4, 2023 at 19:51
  • 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.
    – Lurnobis
    Jan 4, 2023 at 20:43

1 Answer 1


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 %}
  • Wow that made my life fantastically better and drastically simpler. Thanks sonfd.
    – Lurnobis
    Jan 4, 2023 at 18:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.