“While” and “repeat” loops in Twig

被刻印的时光 ゝ 提交于 2020-05-14 15:58:22

问题


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


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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>


来源:https://stackoverflow.com/questions/27691672/while-and-repeat-loops-in-twig

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!