9

Is it possible to break out of a loop in twig? If it is, how would I do it?

2 Answers 2

8

Marion Newlevant wrote a Craft plugin that adds {% break %} and {% continue %} tags to Twig:

https://github.com/marionnewlevant/craft-mnbreakandcontinue

The Craft 3 version is Twig Perversion

1
  • 3
    @nicael certainly not, your answer is definitely the best way to do it without any plugins. Jul 9, 2014 at 18:10
16

Currently there is no special build-in command to do it (unless you want to use a plugin, as stated by Brandon Kelly). There is a workaround, however. The workaround is to check for additional condition.

{% set break = 0 %}

{# this variable we will set to 1 when we do not want code in our loop to run anymore #}

{% for i in 20..100 if break == 0 %} 
    ...
    {# on some condition we will set break to 1 to prevent running of further code #}
    {% set break = 1 %}
    ...
{% endfor %}
5
  • Interesting. Apparently you can use Twig conditional filters as well. Have you run into a practical need for this, or is this a theoretical question?
    – Matt Stein
    Jul 9, 2014 at 16:50
  • @Matt Didn't know about conditional filters. About practical need - yes, finding if number is prime ;-) And nobody forbid you to post an answer about using filters to break from a loop (I won't edit mine because its your idea) :-)
    – nicael
    Jul 9, 2014 at 16:53
  • For reference, it doesn't look like break or continue will ever be part of Twig: github.com/fabpot/Twig/issues/654
    – Brad Bell
    Jul 9, 2014 at 17:29
  • @Brad So exclude "currently"?
    – nicael
    Jul 9, 2014 at 17:30
  • 2
    @nicael - It's still technically accurate. There's always the chance it being missing will annoy us enough that we'll add it in Craft, like we did with {% switch %}.
    – Brad Bell
    Jul 9, 2014 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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