Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a "break" tag to escape a loop in Liquid?

Tags:

liquid

How do I break out of loop in Liquid, mainly a for-loop? I've tried {% break %}, but that fails with There were errors saving your file: Unknown tag 'break'.

I'm trying to achieve something like:

var variants = [];
{% for item in cart.items %}
    {% if item.product.handle == "handle-name" %}
    variants = {{item.product.variants | json}};
    {% break %} // won't work
    {% endif %}
{% endfor %}
like image 682
Lekensteyn Avatar asked Nov 06 '11 15:11

Lekensteyn


People also ask

Does Break get out of for loop?

break terminates the execution of a for or while loop. Statements in the loop after the break statement do not execute. In nested loops, break exits only from the loop in which it occurs.

How do you break out of a loop?

The break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop.

How do you break a loop once condition is met?

In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.

How do you break a loop in console?

You can press Ctrl + C .


1 Answers

For future visitors. Above code does work in current Liquid (gem v2.5.1).

So, you can simply do:

{% for item in cart.items %}
    {% if item.product.handle == "handle-name" %}
    variants = {{item.product.variants | json}};
       {% break %} // This will work
    {% endif %}
{% endfor %}
like image 131
joost Avatar answered Oct 02 '22 13:10

joost