I try to use a simple loop, in my real code this loop is more complex, and I need to break
this iteration like:
{% for post in posts %}
{% if post.id == 10 %}
{# break #}
{% endif %}
<h2>{{ post.heading }}</h2>
{% endfor %}
How can I use behavior of break
or continue
of PHP control structures in Twig?
From docs TWIG docs:
But still:
Example:
You can even use own TWIG filters for more complexed conditions, like:
From @NHG comment — works perfectly
A way to be able to use
{% break %}
or{% continue %}
is to writeTokenParser
s for them.I did it for the
{% break %}
token in the code below. You can, without much modifications, do the same thing for the{% continue %}
.AppBundle\Twig\AppExtension.php:
AppBundle\Twig\BreakToken.php:
AppBundle\Twig\BreakNode.php:
Then you can simply use
{% break %}
to get out of loops like this:To go even further, you may write token parsers for
{% continue X %}
and{% break X %}
(where X is an integer >= 1) to get out/continue multiple loops like in PHP.I have found a good work-around for continue (love the break sample above). Here I do not want to list "agency". In PHP I'd "continue" but in twig, I came up with alternative:
OR I simply skip it if it doesn't meet my criteria:
This can be nearly done by setting a new variable as a flag to
break
iterating:More ugly, but work example for
continue
: