Twig中的"while"和"repeat"循环

Ais*_*tis 9 php loops cycle symfony twig

有什么好的方法可以在Twig中使用和重复循环吗?这是一个如此简单的任务,但没有宏,我找不到任何好看和简单的东西.

至少做一个无限循环,然后在一个条件下打破它?

编辑:

我的意思是

do {
    // loop code
} while (condition)
Run Code Online (Sandbox Code Playgroud)

要么

while (condition) {
    // loop code
}
Run Code Online (Sandbox Code Playgroud)

编辑2:

貌似是因为它不支持既没有原生枝条同样的理由支持它continue;break;语句.

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

小智 10

我能够在树枝上实现一个简单的for循环.所以下面的php语句:

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

当翻译成树枝是:

{% for i in 0..10 %}
    * {{ i }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

这不是一个while循环,而是一个潜在的解决方法.最好的建议是将这样的业务逻辑从模板层中删除.


fre*_*nte 10

您可以for ... in ... if使用足够高的循环限制(10000?)来模拟它

PHP:

$precondition = true;
while ($precondition) {
    $precondition = false;
}
Run Code Online (Sandbox Code Playgroud)

枝条:

{% set precondition = true %}
{% for i in 0..10000 if precondition %}
    {% set precondition = false %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

做的

PHP:

do {
    $condition = false;
} while ($condition) 
Run Code Online (Sandbox Code Playgroud)

枝条:

{% set condition = true %} {# you still need this to enter the loop#}
{% for i in 0..10000 if condition %}
    {% set condition = false %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


Nie*_*jes 8

简而言之:不.此功能意味着高级逻辑,它应该在您的业务逻辑中,而不是在模板层中.这是MVC中关注点分离的一个主要例子.

Twig 完全支持for-loops,如果你正确编码就足够了 - 这是一个复杂的条件决策,决定在它们所属的业务逻辑中显示哪些数据,然后将结果数组"准备渲染"传递给模板.然后,Twig支持渲染所需的所有优秀功能.

  • 问题是我需要打印一个嵌套数组.有一个条件,它必须不递归打印,但**迭代**.我不确定它是否真的如此先进,它应该在后端进行预处理. (6认同)
  • 好吧,这部分在我的答案的前四个字中得到了回答;)Twig 不支持其设计者认为“超出模板引擎范围”的功能,其中包括这些高级循环结构。它只支持 for 循环 - 尽管与范围结构等结合使用时它非常强大。 (2认同)