如何使用break或在Twig模板中的for循环继续? [英] How can I use break or continue within for loop in Twig template?

查看:191
本文介绍了如何使用break或在Twig模板中的for循环继续?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用一个简单的循环,在我的真实代码中,这个循环更加复杂,我需要 break 这样的迭代:

  {%发布在帖子中%} 
{%如果post.id == 10%}
{#break#}
{%endif%}
< h2> {{post.heading}}< / h2>
{%endfor%}

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

解决方案

通过设置一个新变量作为 break 迭代的标志,可以完成

  {%set break = false%} 
{%在帖子中发帖,如果不休息%}
< h2> {{发帖.heading}}< / h2>
{%if post.id == 10%}
{%set break = true%}
{%endif%}
{%end for%}

更难看的是 continue 的工作示例:



$ p $ {code> {%set continue = false%}
{%发表的帖子%}
{%if post.id == 10%}
{%set continue = true%}
{%endif%}
{%if not continue%}
< h2> {{post.heading }}< / H2>
{%endif%}
{%如果继续%}
{%set continue = false%}
{%endif%}
{%endfor%}




但是,没有表现盈利与内置的 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 %}

More ugly, but work 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.

这篇关于如何使用break或在Twig模板中的for循环继续?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆