Iteration tags

Iteration tags are used with collections of keys—objects 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:

Code (key and tag)You’ve already pampered your furry friend with 
{% for purchased in customer.purchased %}
{{ purchased }}
{% endfor %}
OutputYou’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:

  1. {% for senior_pets in new_products.senior_pets %}

  – {{ senior_pets.title }} x {{ senior_pets.price }}

{% endfor %}

  1. {% for senior_pets in products.new_products.senior_pets %}

  – {{ title }} x {{ price }}

{% endfor %}

  1. {% for senior_pets in products.new_products.senior_pets %}

  – {% senior_pets.title %} x {% senior_pets.price %}

{% endfor %}

  1. {% for senior_pets in products.new_products.senior_pets %}

  – {{ senior_pets.title }} x {{ senior_pets.price }}

{% endfor %}

The correct answer is D! 

Let’s run the code:

Code (key and tag){% for senior_pets in products.new_products.senior_pets %}
  – {{ senior_pets.title }} x {{ senior_pets.price }}
{% endfor %}
Output– 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 output (senior_pets.title and senior_pets.price) must be enclosed in double curly braces.