Liquid’s Capture Tag and Numbers
January 6th, 2013
This post is not a tutorial, it’s more of a note for myself that I can refer to in the future. :)
In Liquid, when you use the {% capture %} tag, the variable that you capture becomes a string. As such, if you’re setting up a counter like in the example below, you must apply a math filter on it after to convert it back into a float/integer.
{% assign num = 0 %}
{% for product in product.collections %}
{% if product.tags contains "special" %}
{% capture temp %}{{ num | plus: 1 }}{% endcapture %}
{% endif %}
{% assign num = temp %}
{% endfor %}
{% assign num = num | plus: 0 %}
{% if num > 5 %}
You have more than 5 special products, hooray!
{% endif %}
Thanks as usual to Caro for showing me the ways!
THE END
3 Comments
Tets, I am pretty sure you can do this also:
{% assign num = num | plus: 1 %}
That was not always possible, but I believe it is now.
Holy crap! Just tried it out, and it works. Thanks again, Caro! Changing the code in my post now.
Hi, this is perfect :)
Any chance of storing this variable globally and show it on all other pages and not just this one?