How can I use break or continue within for loop in Twig template?

前端 未结 5 1649
眼角桃花
眼角桃花 2020-12-01 00:35

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 %}
    {% i         


        
5条回答
  •  攒了一身酷
    2020-12-01 01:22

    From docs TWIG docs:

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

    But still:

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

    Example 1 (for huge lists you can filter posts using slice, slice(start, length)):

    {% for post in posts|slice(0,10) %}
        

    {{ post.heading }}

    {% endfor %}

    Example 2:

    {% for post in posts if post.id < 10 %}
        

    {{ post.heading }}

    {% endfor %}

    You can even use own TWIG filters for more complexed conditions, like:

    {% for post in posts|onlySuperPosts %}
        

    {{ post.heading }}

    {% endfor %}

提交回复
热议问题