I am completely stumped by how to count plus one towards a variable assigned via {% assign var = 0 %}
. It should be the most simple task. Here's what I've 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 overlooking something obvious. Maybe there is a better way altogether. All I want to archive is getting the number of iterations that are run.
As {{ increment amount }}
will output your variable value and does not affect a variable defined by {% assign %}
, I suggest you to use {% capture %}
:
{% assign amount = 0 %}
{% for variant in product.variants %}
{% capture amount %}{{ amount | plus:1 }}{% endcapture %}
{% endfor %}
Amount: {{ amount }}
I agree this is verbose, but it's AFAIK the only working solution.
This worked for me and is a bit less verbose:
{% assign amount = 0 %}
{% for variant in product.variants %}
{% assign amount = amount | plus:1 %}
{% endfor %}
Further, it looks like capture
returns a string instead of an integer, making it necessary to cast amount
to an integer if you want to do something like {{if amount >= 10}}
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.