Skip to main content

Iteration Tags

Iteration tags are used with collections of keysobjects and arrays—and allow you to do the same thing for each key without having to write the code more than once. This is also called looping. Let’s say you want to display each product a customer has purchased. You want to display the relevant values, pulling that info from the key. So let’s tell Liquid how to grab the specific info we want.

We’ll use our customer.purchased key again. The array contains seven strings—the names of the seven products the customer has purchased. We’ll use the for tag to loop through the customer.purchased key and insert its values into a sentence:

You’ve already pampered your furry friend with 
{% for purchased in customer.purchased %}
{{ purchased }}
{% endfor %}
You’ve already pampered your furry friend with bowl leash tag bed raincoat doggles vitamins

You’ll notice the missing commas here—in the advanced section we’ll practice combining filters with keys to clean up our copy!

Practice problem: iteration tags

Let’s practice iteration tags with another for tag (sometimes called a for loop). In this problem, we’ll use one to create a list of new senior pet products and their prices.

The keys are products.new_products.senior_pets (a collection of keys that is also an array), products.new_products.senior_pets.title (the products’ titles), and products.new_products.senior_pets.price (the products’ prices). Create a list that shows each product separated from its price with an X.

Select the right Liquid code from the options below:

That’s not right; try again!

The correct answer is D! 

Let’s run the code:

{% for senior_pets in products.new_products.senior_pets %}
  - {{ senior_pets.title }} x {{ senior_pets.price }}
{% endfor %}
- bowl elevator x 15.00- stair steps x 25.00- carry sling x 30.00- senior vitamins x 10.00

Why don’t the other options work?

A) Part of the name of the products.new_products.senior_pets key is missing.

B) The senior_pets.title and senior_pets.price keys are missing parts of their names.

C) The keys (senior_pets.title and senior_pets.price) must be enclosed in double curly braces. 

Up Next: Intermediate Tags – Variable Tags