Basics

Liquid Loops

Loop Structures

Liquid loops use for to iterate Shopify collections or arrays.

Introduction to Liquid Loops

Liquid is a template language created by Shopify and used for rendering dynamic content on Shopify storefronts. One of the core functionalities it provides is the ability to iterate over collections and arrays, which is crucial for displaying lists of products, categories, or any other grouped data. This is achieved using Liquid loops.

In this guide, we will explore how to use the for loop in Liquid to iterate over collections or arrays.

Basic Syntax of Liquid Loops

The for loop in Liquid allows you to iterate over a collection or array. Here is the basic syntax:

{% raw %}{% for item in collection %} {{ item }} {% endfor %}{% endraw %}

The loop starts with {% for item in collection %} and ends with {% endfor %}. Within the loop, you can perform operations or display data for each item.

Iterating Over Shopify Collections

In Shopify, you might want to display a list of products or collections on your store. Here’s how you can use Liquid loops to do that:

For example, to list all products in a collection:

In this example, the loop iterates over each product in the collection.products array, and for each product, it outputs the product's title and price.

Iterating Over Arrays

Liquid loops are not limited to collections. You can also iterate over simple arrays:

Here, we first create an array of colors by splitting a comma-separated string. Then, we loop over each color and output it inside a paragraph.

Using Loop Variables

Liquid provides several helpful variables within a loop, such as forloop.index and forloop.first. These can be used to add logic within your loops:

In this example, we use forloop.index to display the position of each product, and forloop.first to check if the current item is the first in the list.

Conclusion

Liquid loops are a powerful tool for iterating over collections and arrays, allowing you to dynamically display lists of data on your Shopify store. By mastering loops, you can create more engaging and dynamic themes that enhance the shopping experience for your customers.

Previous
Case