Tags

Liquid Cycle Tag

Using Cycle Tag

Liquid cycle tag alternates values in Shopify loops for styling.

Introduction to Liquid Cycle Tag

The Liquid cycle tag is a powerful tool in Shopify's templating language that allows developers to alternate between different values within loops. This is especially useful for styling purposes, such as alternating row colors in tables or applying different classes to elements in a list.

Basic Syntax of the Cycle Tag

The basic syntax for the cycle tag in Liquid is as follows:

{% cycle value1, value2, value3, ... %}

In a loop, the cycle tag will rotate through the values provided, returning a different one each time it's called.

Using Cycle Tag in a Loop

Let's look at an example of how the cycle tag can be used within a for loop to alternate class names for styling list items:

{% for i in (1..5) %}
  <li class="{% cycle 'odd', 'even' %}">Item {{ i }}</li>
{% endfor %}

In this example, each <li> element alternates between having the class "odd" and "even". This can be useful for styling purposes, such as giving alternating background colors to list items.

Advanced Usage with Cycle Tag

The cycle tag can also be used with named cycles to allow multiple cycles within the same loop. This is done by providing a name before the values:

{% cycle 'name': value1, value2, value3 %}

Using named cycles, you can alternate through multiple sets of values without them interfering with each other.

Example of Named Cycles

Consider the following example where named cycles are used to style a table:

{% for product in products %}
  <tr class="{% cycle 'row': 'row-odd', 'row-even' %}">
    <td>{{ product.name }}</td>
    <td class="{% cycle 'price': 'price-low', 'price-high' %}">{{ product.price | money }}</td>
  </tr>
{% endfor %}

In this scenario, we have two different cycles: one for alternating the row class and another for alternating the price class.

Conclusion

The Liquid cycle tag is a versatile tool for developers working with Shopify templates. By alternating values within loops, you can create dynamic and visually appealing designs. Whether you're styling lists, tables, or any other repeated elements, the cycle tag provides a straightforward way to manage alternating attributes efficiently.

Previous
Raw Tag