简体   繁体   中英

"While" and "repeat" loops in Twig

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

I was able to implement a simple for loop in twig. So the following php statement:

for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
}

when translated to twig is:

{% for i in 0..10 %}
    * {{ i }}
{% endfor %}

It's not a while loop but a potential workaround. The best suggestion is to leave business logic like this out of the template layer.

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 %}

In a nutshell: no. This functionality implies advanced logic, which should be in your business logic, not in the template layer. It's a prime example of the separation of concerns in MVC.

Twig supports for -loops completely, which should suffice if you code correctly - being that complex conditional decisions on which data to display are taken in the business logic where they belong, which then pass a resulting array 'ready to render' to the templates. Twig then supports all nice features only needed for rendering.

This is possible, but a little bit complicated.

You can use {% include ... %} to process nested arrays, which from the comments I read is what you need to do.

Consider the following code:

nested_array_display.html

<ul>
{% for key, val in arr %}
    <li>
        {{ key }}:
{% if val is iterable %}
{% include 'nested_array_display.html' %}
{% else %}
        {{ val }}
{% endif %}
    </li>
{% endfor %}
</ul>

Warning with the top solution with "high loop limit": the loop doesn't break when the condition returns false, it just doesn't enter the loop. So the loop runs up to the high indice

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM