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.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
up vote 7 down vote accepted

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

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

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 '14 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 '14 at 16:53
For reference, it doesn't look like break or continue will ever be part of Twig: – Brad Bell Jul 9 '14 at 17:29
@Brad So exclude "currently"? – nicael Jul 9 '14 at 17:30
@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 '14 at 17:32

Your Answer


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.