Peter Peter - 23 days ago 5
PHP Question

How to stop or break free from a Twig loop?

In PHP you've got the possibility to break from a loop or continue to the next iteration. I was wondering if you've got the same functionality in Symfony's Twig.

For example, in PHP I am able to do:

foreach ($array as $key => $value) {
if ($value == 'something') {
continue;
} elseif ($value == 'somethingElse') {
break;
}
echo $value;
}


Is there something similiar in Twig? For example something like:

{% for value in array %}
{% if value == 'something' %}
{% continue %}
{% endif %}
{% if value == 'somethingElse' %}
{% break %}
{% endif %}
{{ value }}
{% endfor %}

Answer

No, Twig does not offer a method to break from a loop.

From the docs -

Unlike in PHP, it's not possible to break or continue in a loop. You can however filter the sequence during iteration which allows you to skip items. The following example skips all the users which are not active:

Comments