Peter Peter - 3 months ago 25
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') {
} elseif ($value == 'somethingElse') {
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 %}


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: