Liquid Variables: assign, capture, increment, increment in Shopify

Now, let’s take a look at our instructional writing on Liquid Variables: assign, capture, increment, increment to know more deeply about this topic.

Liquid Variables

Liquid Variables

Variable tags can generate new Liquid variables.

assign

Can generate a new variable.

Input

{% assign my_variable = false %}
{% if my_variable != true %}
  This statement is valid.
{% endif %}

Output

  This statement is valid.

Wrap a variable in quotations " to save it as a string.

Input

{% assign foo = "bar" %}
{{ foo }}

Output

bar

capture

Can capture the string inside of the closing and opening tags and then assigns it to a variable. Variables generated through {% capture %} are strings.

Input

{% capture my_variable %}I am being captured.{% endcapture %}
{{ my_variable }}

Output

I am being captured.

You are allowed to generate complicated strings using other variables created with assign by using capture.

Input

{% assign favorite_food = 'pizza' %}
{% assign age = 35 %}

{% capture about_me %}
I am {{ age }} and my favorite food is {{ favorite_food }}.
{% endcapture %}

{{ about_me }}

Output

I am 35 and my favourite food is pizza.

increment

Able to generate a new number variable, and raises its value by one every time it is called. The initial value is 0.

Input

{% increment my_counter %}
{% increment my_counter %}
{% increment my_counter %}

Output

0
1
2

Variables that are created through the increment tag are independent from variables, which are gennerated through assign or capture.

A variable called “var” is generated through assign in the example taken below. The increment tag is then used several times on a variable with the similar name. Note that the increment tag does not affect the value of “var” that was created through assign.

Input

{% assign var = 10 %}
{% increment var %}
{% increment var %}
{% increment var %}
{{ var }}

Output

0
1
2
10

decrement

Able to generate a new number variable, and reduces its value by one every time it is called. The initial value is -1.

Input

{% decrement variable %}
{% decrement variable %}
{% decrement variable %}

Output

-1
-2
-3

Similar to increment, variables declared inside decrement are also independent from variables, which are generated through assign or capture.

Using Liquid Variables

ND

Conclusion

ND