Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

liquid - unless for.loop always seems to be last

Consider this below:

{% for variant in product.variants %}
    {{ forloop.index }}<br>
    {{ unless forloop.last }}LAST<br>{{ endunless }}
{% endfor %}

According to the shopify docs:

Returns true if it's the last iteration of the for loop. Returns false if it is not the last iteration.

The output of the code above is: (for 3 variants)

1
LAST
2
LAST
3
LAST

Why? Is the variant object different from the others in context of forloop.last?


1 Answers

You have delimited your unless query with double curly brace delimiters rather than curly brace percentage delimiters. As such, they don't form a conditional scope around the literal value LAST which is thus always added (ignoring the conditional).

If you use the correct brace style for conditions, it should work correctly:

{% for variant in product.variants %}
    {{ forloop.index }}<br>
    {% unless forloop.last %}LAST<br>{% endunless %}
{% endfor %}

See the documentation for details.

like image 165
Holger Just Avatar answered Dec 13 '25 12:12

Holger Just



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!