{% 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 and continue statements like in flat PHP. 这篇关于如何在 Twig 模板的 for 循环中使用 break 或 continue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-06 13:48