Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count variable +1 in Liquid

Tags:

ruby

liquid

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.

like image 270
herrbischoff Avatar asked May 16 '15 10:05

herrbischoff


People also ask

What is variable count?

The Counting Variable keeps track of the number of times the Repeat Dialog (or Loop) has been repeated. The number associated with a particular loop constitutes the value of the Counting Variable. That value is then appended to each variable name used in a Question which is part of that loop.

How do you assign a Javascript variable to a liquid?

Unfortunately, you cannot assign JS variables to Liquid variables. The reason is Liquid is processed at serverside. What you can do is, create an element with JS and push that JS variable content to that element if you need to show the JS content on a page.


1 Answers

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.

like image 75
zessx Avatar answered Nov 14 '22 20:11

zessx