php – 如何在Twig模板中的for循环中使用break或continue?

我试图使用一个简单的循环,在我的实际代码这个循环是更复杂,我需要打破这个迭代喜欢:

{% for post in posts %}
    {% if post.id == 10 %}
        {# break #}
    {% endif %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

如何在Twig中使用break或继续PHP控制结构的行为?

来自docs TWIG docs

Unlike in PHP, it’s not possible to break or continue in a loop.

但还是:

You can however filter the sequence during iteration which allows you to skip items.

例:

{% for post in posts if post.id < 10 %}
    <h2>{{ post.heading }}</h2>
{% endfor %}

你甚至可以使用自己的TWIG filters更复杂的条件,如:

{% for post in posts|onlySuperPosts %}
    <h2>{{ post.heading }}</h2>
{% endfor %}
http://stackoverflow.com/questions/21672796/how-can-i-use-break-or-continue-within-for-loop-in-twig-template

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:php – 如何在Twig模板中的for循环中使用break或continue?