如何在 Twig 模板的 for 循环中使用 break 或 continue? [英] How can I use break or continue within for loop in Twig template?
本文介绍了如何在 Twig 模板的 for 循环中使用 break 或 continue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用一个简单的循环,在我的实际代码中,这个循环更复杂,我需要像这样break
这个迭代:
{% for post in posts %}{% if post.id == 10 %}{# 休息 #}{% 万一 %}<h2>{{ post.heading }}</h2>{% 结束为 %}
如何在 Twig 中使用 PHP 控制结构的 break
或 continue
行为?
解决方案
这可以几乎通过设置一个新变量作为break
迭代的标志来完成:>
{% set break = false %}{% for post in post if not break %}<h2>{{ post.heading }}</h2>{% if post.id == 10 %}{% 设置中断 = 真%}{% 万一 %}{% 结束为 %}
continue
一个更丑但有效的例子:
{% set continue = false %}{% 用于帖子中的帖子 %}{% if post.id == 10 %}{% set continue = true %}{% 万一 %}{% 如果不继续 %}<h2>{{ post.heading }}</h2>{% 万一 %}{% 如果继续 %}{% 设置继续 = false %}{% 万一 %}{% 结束为 %}
<块引用>
但是没有没有的性能收益,只有与内置的break
和continue
语句类似的行为,就像在平面PHP中一样.>
I try to use a simple loop, in my real code this loop is more complex, and I need to break
this iteration like:
{% for post in posts %}
{% if post.id == 10 %}
{# break #}
{% endif %}
<h2>{{ post.heading }}</h2>
{% endfor %}
How can I use behavior of break
or continue
of PHP control structures in Twig?
解决方案
This can be nearly done by setting a new variable as a flag to break
iterating:
{% set break = false %}
{% for post in posts if not break %}
<h2>{{ post.heading }}</h2>
{% if post.id == 10 %}
{% set break = true %}
{% endif %}
{% endfor %}
An uglier, but working example for continue
:
{% set continue = false %}
{% for post in posts %}
{% if post.id == 10 %}
{% set continue = true %}
{% endif %}
{% if not continue %}
<h2>{{ post.heading }}</h2>
{% endif %}
{% if continue %}
{% set continue = false %}
{% endif %}
{% endfor %}
But there is no performance profit, only similar behaviour to the built-in
break
andcontinue
statements like in flat PHP.
这篇关于如何在 Twig 模板的 for 循环中使用 break 或 continue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文