How can I use break or continue within for loop in Twig template?

break, for-loop, php, symfony, twig

Solution

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` and `continue` statements like in flat PHP.

Problem

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?

Original source