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?
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter).
loop.index0. The current iteration of the loop. ( 0 indexed) loop.revindex. The number of iterations from the end of the loop (1 indexed)
This can be nearly done by setting a new variable as a flag to break
iterating:
{% set break = false %} {% for post in posts if not break %} <h2>{{ post.heading }}</h2> {% if post.id == 10 %} {% set break = true %} {% endif %} {% endfor %}
An uglier, but working example for continue
:
{% set continue = false %} {% for post in posts %} {% if post.id == 10 %} {% set continue = true %} {% endif %} {% if not continue %} <h2>{{ post.heading }}</h2> {% endif %} {% if continue %} {% set continue = false %} {% endif %} {% endfor %}
But there is no performance profit, only similar behaviour to the built-in
break
andcontinue
statements like in flat PHP.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With