Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use break or continue within for loop in Twig template?

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?

like image 776
Victor Bocharsky Avatar asked Feb 10 '14 09:02

Victor Bocharsky


People also ask

How do you break inside a for loop?

When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter).

What is loop index0?

loop.index0. The current iteration of the loop. ( 0 indexed) loop.revindex. The number of iterations from the end of the loop (1 indexed)


1 Answers

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.

like image 82
Victor Bocharsky Avatar answered Oct 19 '22 13:10

Victor Bocharsky