"Bye" and "repeat" loops in Twig

Are there any good ways to use while and repeat loop in Twig? This is such a simple task, but without macros I cannot find anything pleasant and simple.

At least do an infinite loop and then fold it in a state?

EDIT:

I mean something like

do { // loop code } while (condition) 

or

 while (condition) { // loop code } 

Edit 2:

It seems that it is not supported initially by the branch, since it is not supported by any continue; statements continue; nor break; .

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

+7
loops php cycle symfony twig
source share
4 answers

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

Twig fully supports for -loops , which should be enough if you code correctly - these are complex conditional solutions by which the data for display is taken in the business logic where they belong, which then pass the resulting array โ€œready to renderโ€ to the templates. Twig then supports all the nice features that are only needed for rendering.

+6
source share

I managed to implement a simple loop in twig. So the following php statement:

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

when transferring to a branch:

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

This is not a while loop, but a potential workaround. The best suggestion is to leave the business logic this way from the template layer.

+6
source share

You can emulate it with for ... in ... if using the maximum loop limit (10000?)

, but

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 %} 
+4
source share

It is possible, but a little more complicated.

You can use {% include ... %} to process nested arrays, which from the comments I read are 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> 
0
source share

All Articles