Variable

Variable tags are used to create and manipulate variables in Liquid. They allow you to store data and perform operations on variables that can be used throughout your template. The following tags are available for working with variables: assign, capture, decrement, and increment.

assign

The assign tag is used to create a new variable or update the value of an existing variable. The syntax for the assign tag is:

{% assign variable_name = value %}

Example: Assigning a variable named discount with a value of 10

{% assign discount = 10 %}

You can also use expressions or other variables when assigning a value:

{% assign discounted_price = product.price * (1 - discount / 100) %}

Capture

The capture tag is used to store the output of a block of Liquid code in a variable. The syntax for the capture tag is:

{% capture variable_name %}
  Liquid code to be captured
{% endcapture %}

Example: Capturing the output of a loop in a variable named product_list

{% capture product_list %}
  <ul>
    {% for product in products %}
      <li>{{ product.title }}</li>
    {% endfor %}
  </ul>
{% endcapture %}

You can then use the product_list variable elsewhere in your template:

<div class="product-list">
  {{ product_list }}
</div>

Decrement

The decrement tag is used to decrease the value of a variable by 1. If the variable doesn't exist, it will be created and set to -1. The syntax for the decrement tag is:

{% decrement variable_name %}

Example: Decrementing a variable named counter

{% decrement counter %}

Increment

The increment tag is used to increase the value of a variable by 1. If the variable doesn't exist, it will be created and set to 1. The syntax for the increment tag is:

{% increment variable_name %}

Example: Incrementing a variable named counter

{% increment counter %}

By using these variable tags, you can create, manipulate, and store data in your Liquid templates, making it easier to perform calculations, create reusable content, and manage the state of your application.

Last updated