Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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

like image 837
Aistis Avatar asked Dec 29 '14 15:12

Aistis


4 Answers

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 %}
like image 128
fregante Avatar answered Nov 19 '22 08:11

fregante


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.

like image 32
Niels Keurentjes Avatar answered Nov 19 '22 09:11

Niels Keurentjes


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.

like image 10
DslDip Avatar answered Nov 19 '22 10:11

DslDip


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>
like image 2
Xesau Avatar answered Nov 19 '22 10:11

Xesau