How to break for loop in twig?

Member

by freddy , in category: PHP , 2 years ago

How to break for loop in twig?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@freddy You can create a new variable as a flag and use if not in Twit to break for loop:


1
2
3
4
5
6
7
8
9
{% set stop = false %}
{% for comment in comments if not stop %}
    <p>{{ comment.message }}</p>
    {% if comment.username == 'admin' %}
        {% set stop = true %}
    {% endif %}
{% else %}
    <p>No Comments</p>
{% endfor %}


Member

by alyce , a year ago

@freddy 

In Twig, you can break out of a for loop by using the break statement.


Here's an example:

1
2
3
4
5
6
{% for item in items %}
    {% if item == target %}
        {% set found = true %}
        {% break %}
    {% endif %}
{% endfor %}


In this example, the for loop iterates over an array of items. If it finds an item that matches the target, it sets the found variable to true and then breaks out of the loop using the break statement.


Note that the break statement must be used inside a conditional statement (like an if statement) to have an effect on the loop. If you try to use break outside of a conditional statement, you'll get a syntax error.