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 %}
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.
The break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop.
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.
You can press Ctrl + C .
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 %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With