0

Does anyone know how to loop through an array and find the first of an item then break the loop in twig?

Like this

Loop->find 3
- 2
- 2
- 3 - then break loop here
- 1
- 3
DarkBee
  • 16,592
  • 6
  • 46
  • 58
  • 2
    Does this answer your question? [How can I use break or continue within for loop in Twig template?](https://stackoverflow.com/questions/21672796/how-can-i-use-break-or-continue-within-for-loop-in-twig-template) – Mukesh Singh Thakur Mar 05 '20 at 04:51

1 Answers1

2

Try this code. It's working on the twig <= 2 version.

    {% set break = false %}
    {% set numbers = [2,2,3,1,3] %}
    {% for number in numbers if not break %}
       - {{ number }} <br/>
        {% if number == 3 %}
            {% set break = true %}
        {% endif %}
    {% endfor %}

But in Twig 3, it's not working. You can try the below code it's working for twig 3.

        {% set break = false %}
        {% set numbers = [2,2,3,1,3] %}
        {% for number in numbers %}
            {% if break == false %}
                - {{ number }} <br/>
                {% if number == 3 %}
                    {% set break = true %}
                {% endif %}
            {% endif %}
        {% endfor %}

I have read the twig 3 document but I can't fine break/continue concept on that.

=> Output

- 2
- 2
- 3 
Mukesh Singh Thakur
  • 1,335
  • 2
  • 10
  • 23