Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers 2

up vote 6 down vote accepted

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

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

share|improve this answer
    
So my answer is invalid? –  nicael Jul 9 at 17:49
2  
@nicael certainly not, your answer is definitely the best way to do it without any plugins. –  Brandon Kelly Jul 9 at 18:10
add comment

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 %}
share|improve this answer
    
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 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 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 at 17:29
    
@Brad So exclude "currently"? –  nicael Jul 9 at 17:30
1  
@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 at 17:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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