How to calculate the +1 variable in a liquid

I completely tainted how to count plus one in relation to the variable assigned through {% assign var = 0 %} . This should be the easiest task. Here is what I have tried so far:

 {% assign amount = 0 %} {% for variant in product.variants %} {% assign amount = amount + 1 %} {% endfor %} Amount: {{ amount }} 

The result is always 0 . Maybe I'm losing sight of something obvious. Maybe there is a better way. All I want to archive is the number of iterations started.

+5
source share
2 answers

Since {{ increment amount }} outputs your variable value, and does not affect the variable defined by {% assign %} , I suggest you use {% capture %} :

 {% assign amount = 0 %} {% for variant in product.variants %} {% capture amount %}{{ amount | plus:1 }}{% endcapture %} {% endfor %} Amount: {{ amount }} 

I agree that this is verbose, but AFAIK is the only working solution.

+5
source

This worked for me and a little less verbose:

 {% assign amount = 0 %} {% for variant in product.variants %} {% assign amount = amount | plus:1 %} {% endfor %} 

Also, it seems that capture returns a string instead of an integer, which makes it necessary to cast amount to an integer if you want to do something like {{if amount >= 10}} .

+3
source

All Articles