129

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?

0

5 Answers 5

174

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.

8
  • 1
    It is useful. In my case I just need to show / get the first result. Is there a way in Twig to get just the first value? This is only for better performance purposes.
    – Pathros
    Commented Feb 11, 2016 at 15:27
  • 1
    @pathros In order to get the first value, use the first twig filter: twig.sensiolabs.org/doc/filters/first.html Commented Feb 11, 2016 at 20:21
  • 3
    It's worth noting that this will not break the code execution, anything below set break = true will be executed unless you put it in an else statement. See twigfiddle.com/euio5w
    – Gus
    Commented Nov 3, 2017 at 12:27
  • 2
    @Gus Yep, that's why I was meaning to put that if statement with set break = true in the very end. But yeah, it depends on your code, so thanks for mentioning it to clarify Commented Nov 4, 2017 at 19:46
  • 4
    I use twig 3.x and had an issue with this method if not break I've got this error Uncaught Twig\Error\SyntaxError: Unexpected token "name" of value "if"
    – ZenithS
    Commented May 18, 2022 at 3:56
148

From docs TWIG 2.x docs:

Unlike in PHP, it's not possible to break or continue in a loop.

But still:

You can however filter the sequence during iteration which allows you to skip items.

Example 1 (for huge lists you can filter posts using slice, slice(start, length)):

{% for post in posts|slice(0,10) %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

Example 2 works TWIG 3.0 as well:

{% for post in posts if post.id < 10 %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

You can even use own TWIG filters for more complexed conditions, like:

{% for post in posts|onlySuperPosts %}
    <h2>{{ post.heading }}</h2>
{% endfor %}
13
  • 28
    Moreover if you wanna achive break loop after 10 iteration you could use sth like that: {% for post in posts|slice(0,10) %}
    – NHG
    Commented Feb 10, 2014 at 9:20
  • 5
    OK, thanks, I probably missed Unlike in PHP, it's not possible to break or continue in a loop. when read the docs. But I think break and continue is a good features, which would need to add Commented Feb 10, 2014 at 9:35
  • You can't access loop variable in the loop statement!
    – Maximus
    Commented May 15, 2017 at 18:37
  • doesn't work. long list, for should be breakable after first hit. @VictorBocharsky 's answer is right Commented Feb 20, 2019 at 16:19
  • 6
    A heads up, while it's available in 2.0, Twig removed the {% for ... if ... %} statement in version 3.0. Commented May 20, 2021 at 15:43
16

A way to be able to use {% break %} or {% continue %} is to write TokenParsers 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:

    namespace AppBundle\Twig;
    
    class AppExtension extends \Twig_Extension
    {
        function getTokenParsers() {
            return array(
                new BreakToken(),
            );
        }
    
        public function getName()
        {
            return 'app_extension';
        }
    }
    
  • AppBundle\Twig\BreakToken.php:

    namespace AppBundle\Twig;
    
    class BreakToken extends \Twig_TokenParser
    {
        public function parse(\Twig_Token $token)
        {
            $stream = $this->parser->getStream();
            $stream->expect(\Twig_Token::BLOCK_END_TYPE);
    
            // Trick to check if we are currently in a loop.
            $currentForLoop = 0;
    
            for ($i = 1; true; $i++) {
                try {
                    // if we look before the beginning of the stream
                    // the stream will throw a \Twig_Error_Syntax
                    $token = $stream->look(-$i);
                } catch (\Twig_Error_Syntax $e) {
                    break;
                }
    
                if ($token->test(\Twig_Token::NAME_TYPE, 'for')) {
                    $currentForLoop++;
                } else if ($token->test(\Twig_Token::NAME_TYPE, 'endfor')) {
                    $currentForLoop--;
                }
            }
    
    
            if ($currentForLoop < 1) {
                throw new \Twig_Error_Syntax(
                    'Break tag is only allowed in \'for\' loops.',
                    $stream->getCurrent()->getLine(),
                    $stream->getSourceContext()->getName()
                );
            }
    
            return new BreakNode();
        }
    
        public function getTag()
        {
            return 'break';
        }
    }
    
  • AppBundle\Twig\BreakNode.php:

    namespace AppBundle\Twig;
    
    class BreakNode extends \Twig_Node
    {
        public function compile(\Twig_Compiler $compiler)
        {
            $compiler
                ->write("break;\n")
            ;
        }
    }
    

Then you can simply use {% break %} to get out of loops like this:

{% for post in posts %}
    {% if post.id == 10 %}
        {% break %}
    {% endif %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

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.

8
  • 14
    That's just overkill. Twig loops should be supporting breaks and continues natively.
    – crafter
    Commented Mar 4, 2017 at 23:27
  • This is nice if you don't want to/can't use filters. Commented Mar 8, 2018 at 12:17
  • 1
    The squirrelphp/twig-php-syntax library provides {% break %}, {% break n %} and {% continue %} tokens. Commented Aug 7, 2020 at 10:30
  • 1
    @mtsknn and the authors used and improved the code that I wrote for this answer! Commented Aug 18, 2020 at 9:27
  • @JulesLamur, you said "@mtsknn and the authors," but I'm not involved with that library. Commented Aug 18, 2020 at 9:54
8

From @NHG comment — works perfectly

{% for post in posts|slice(0,10) %}
2
  • @Basit if posts are ordered by date? Commented Feb 21, 2019 at 11:09
  • −1. Will not work in a lot of cases. For instance, in the OP’s code, what if posts aren’t ordered by id, or if there is no post for some ids? Commented Jul 4, 2022 at 8:41
6

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:

{% for basename, perms in permsByBasenames %} 
    {% if basename == 'agency' %}
        {# do nothing #}
    {% else %}
        <a class="scrollLink" onclick='scrollToSpot("#{{ basename }}")'>{{ basename }}</a>
    {% endif %}
{% endfor %}

OR I simply skip it if it doesn't meet my criteria:

{% for tr in time_reports %}
    {% if not tr.isApproved %}
        .....
    {% endif %}
{% endfor %}

Not the answer you're looking for? Browse other questions tagged or ask your own question.