Tetchi x Wordpress

Liquid’s Capture Tag and Numbers

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

Ognjen Knaus

February 18th, 2015

Hi, this is perfect ๐Ÿ™‚

Any chance of storing this variable globally and show it on all other pages and not just this one?

tetchi

February 24th, 2013

Holy crap! Just tried it out, and it works. Thanks again, Caro! Changing the code in my post now.

Caroline Schanpp

February 21st, 2013

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.