"While" and "repeat" loops in Twig

Aistis picture Aistis · Dec 29, 2014 · Viewed 28.8k times · Source

Are there any nice ways to use while and repeat loops in Twig? It is such a simple task, but without macros I can't find anything nice and simple.

At least do an infinite cycle and then break it in a condition?

EDIT:

I mean something like

do {
    // loop code
} while (condition)

or

while (condition) {
    // loop code
}

Edit 2:

Looks like it is not supported natively by twig same reason as it is not supported neither continue; or break; statements.

https://github.com/twigphp/Twig/issues/654

Answer

fregante picture fregante · Jan 16, 2017

You can emulate it with for ... in ... if by using a sufficiently-high loop limit (10000?)

while

PHP:

$precondition = true;
while ($precondition) {
    $precondition = false;
}

Twig:

{% set precondition = true %}
{% for i in 0..10000 if precondition %}
    {% set precondition = false %}
{% endfor %}

do while

PHP:

do {
    $condition = false;
} while ($condition) 

Twig:

{% set condition = true %} {# you still need this to enter the loop#}
{% for i in 0..10000 if condition %}
    {% set condition = false %}
{% endfor %}