Category: Liquid Tutorial

Using Liquid in Customer.io

As we’ve discussed, there are many “flavors” of Liquid—and while you may encounter some variation in the terminology that’s used, the principles are all the same. Of course, Customer.io has its own Liquid flavor, tailored to personalize your emails! Here are some of the highlights you might want to explore next:

We also have some handy “recipes” for certain use cases; here are a few fun ones:

Now that you’re armed with a core understanding of the three elements of Liquid and how they work together, you can go out into the wilds and explore whatever flavor of Liquid you find there. Have fun getting super personal with your content—and driving higher engagement and conversation!

For loops

You already know that you can use the for tag (also called a for loop) to iterate (aka, “loop”) over arrays and objects. A common use case for a for loop is listing each item a customer purchased in a transactional email. In this section, we’ll take a deeper dive into for loops so you can use them with greater precision to get better results with your emails.

Looping over objects and arrays

Arrays contain an ordered list of string or number values or an ordered list of objects (a collection of key/value pairs). Great news—you’ve already learned how to loop over an array of objects! Here’s the example you practiced on in Module 5:

Code{% 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

Products.new_products is an array, and each product—senior_pets—is an object that contains key/value pairs. In this case, senior_pets is just the name we’ve assigned the object; the first item in the for loop syntax just defines the context, so you something like “for <x> in <y>” just defines the objects in the array as “<x>”.

For loops can also iterate over an array of string or number values. Let’s look at a loop over an array of strings:

Code {% assign items = “leash, bowl, collar” | split: “, ” %}
{% for item in items %}  {{ item }}{% endfor %}
Outputleashbowlcollar

The for loop iterates through the array and outputs a list of its values. The second, third, and fourth lines of code above are the for loop tag.

A little detour to look at that first line of code, just so you know what you’re looking at:

  • We’ve used the assign tag to store a value in our code. In this case, the data type of the value type is a string.
  • But we know that the values need to be in a specific order so the for loop can iterate over them. So we’ve used the split filter to convert that string into an array—an ordered list of info. 
    • What about that comma and space between the quotation marks? That’s the delimiter the split filter will use to recognize and the individual bits of info in the string—when it sees the comma and space between the items in “leash, bowl, collar” it knows to split the string at those points

Looping over hashes

We taled about the concept of hashing as part of encryption schemes earlier in this module. the term hash can also refer to a data structure in Ruby (Liquid’s parent language) that is essentially—although not exactly—the same as a JavaScript object. You can use Liquid to iterate over hashes, and the syntax is slightly different. Here’s a primer on how to loop over hashes.

For loop helper tags

The for tag has several “helper” tags: else, break and continue. They give you more control over loops and more options for using them.

The else tag defines an alternative output if you loop over an empty array—instead of a blank line. Here’s how it looks:

Code {% assign items = empty %}
{% for item in items %}  {{ item }}{% else %}This array is empty.{% endfor %}
OutputThis array is empty.

Since the loop cannot run over the empty array, it displays the alternative output. You might use else to avoid extra lines in your emails when keys are unexpectedly empty.    

Break and continue allow you to stop looping or skip a value. To use them, nest an if/else or elsif/else tag within your for tag. Let’s start by looking at break:

Code {% assign items = “leash, bowl, collar” | split: “, ” %}
{% for item in items %}
    {% if item == “bowl” %}    {% break %}    {% else %}  {{ item }}    {% endif %}
{% endfor %}
Outputleash

Let’s walk through what the Liquid code is doing:

Line 1: Assign creates a new key and stores its value. This value is an array.

Line 2: Loop over these keys, starting at the first one in the array.

Line 3: This opens the condition tag, which checks the item value against the condition.

Line 4: If the condition in Line 3 is met, stop (break). The loop is over.

Line 5: If the condition in Line 3 is not met, display the key’s value.

Line 6: Close the elsif/if tag.

Line 7: Close the for tag.

When the code runs, it checks the first value in the array to see if it equals “bowl”. If it doesn’t, the code loops over that value and displays it. Then the code runs again, starting at the second value in the array. It will keep looping until it finds “bowl” or reaches the end of the array. In this example, the code can only loop once, because “bowl” is the second value in the array.

Now let’s try the continue tag. It skips over a value in an array that meets a condition. We’ll use the same example as before: 

Code {% assign items = “leash, bowl, collar” | split: “, ” %}
{% for item in items %}
    {% if item == “bowl” %}    {% continue%}    {% else %}  {{ item }}    {% endif %}
{% endfor %}
Outputleashcollar

Here, when the next value in the array equals “bowl”, the code skips that value and starts again with the next value in the array’s sequence. It loops until it reaches the last value in the array.

The break and continue tags have a lot of handy uses when personalizing emails. Say a customer has bought a bowl, and you want to recommend related products without repeating the product they already bought—the continue tag makes it happen!  

For loop parameters: limit, offset, and reversed

There are three parameters that you can use with for loops: reversed, limit, and offset. Just as we discussed when describing localization tools, parameter in this context means an extra instruction that customizes the for loop to your needs.  

Reversed begins the loop at the last item in the array’s sequence, rather than the first.

Code {% assign items = “leash, bowl, collar” | split: “, ” %}
{% for item in items reversed %}  {{ item }}{% endfor %}
Outputcollarbowlleash

Notice that reversed is not separated with a pipe character–these parameters are not filters

Limit allows you to specify a number of iterations, rather than iterating until a break condition is met or the last item in the array. 

Code {% assign items = “leash, bowl, collar” | split: “, ” %}
{% for item in items limit:2 %}  {{ item }}{% endfor %}
Outputleashbowl

Limit must be followed by a colon and an integer (no spaces). The integer tells the for loop how many iterations to complete. Because we limited this loop to 2 iterations, only the first two values in the array are output.

Offset allows you to begin a loop at a specific index, or point in the sequence, rather than at 0, the first item in the sequence.

Code {% assign items = “leash, bowl, collar” | split: “, ” %}
{% for item in items offset:2 %}  {{ item }}{% endfor %}
Outputcollar

You must follow offset with a colon and an integer (no spaces). The integer represents the position in the array at which the loop should start. Here, we’ve entered 2, so the loop will skip the first two positions in the array, start at the third position, and run until the end of the array. 

You can combine reversed, offset, and limit in the same line of code, like this: 

{% for item in items reversed limit:3 offset:2 %}. 

However, if you include reversed, it must come before limit and offset. The order of limit and offset doesn’t matter. 

Whitespace control

Nothing gives away badly coded emails like extra spaces where they don’t belong. That’s where whitespace control comes in! You learned in Liquid Fundamentals that you can use filters to manage unwanted whitespace in your output. Most Liquid flavors will offer the lstrip, rstrip, and strip filters, which take out whitespace to the right or left (or both the right and left at once) of your output.

Another way to manage whitespace is simply by adding hyphens to your notation (aka, the characters with which you enclose your code). You can do this with either a key or a tag. Here’s what the notation looks like for a key if you want to remove any whitespace at the beginning and end of your output: 

{{- customer.first_name -}}

You can also just use one hyphen on either the left or right side of your notation if you just want to strip out whitespace at the beginning or end of your output, like this:

{{- customer.first_name }}

{{ customer.first_name -}}

Voila! A handy way to make sure you don’t have unwanted whitespace without needing to use a strip filter

You can do this exact same trick with the notation for tags. This is especially handy for ensuring you don’t have extra blank lines in your output. Some Liquid flavors (including Shopify’s) will print a blank line for each line of Liquid code, even those that don’t output text (like most tags). That can add many extra lines in your email. You can avoid the problem by adding a hyphen to the right-hand notation of your tags, like this:

Code {% assign my_variable = “Good dog!” -%}{{ my_variable }}
Output Good dog!

Experiment with your flavor of Liquid before adding hyphens to your code. Not all flavors add extra line breaks, so you might be making extra work for yourself if you don’t check first!

Encoding, hashing, and encryption schemes

Sometimes you may need to encode or hash values—or use hashes in an encryption scheme. Liquid filters can help you do that! We’ll give you a tour of the whys and whats here; then you can dive deeper in this Auth0.com article. You’ll know when you need to use the filters below because whatever you’re trying to do will explicitly state that you need to encode or hash certain values. 

Encoding

Encoding transforms a value for data-handling purposes—it’s not related to information security. For example, we encode strings containing special characters to make them URL-safe (aka, containing only characters that can be transmitted over the internet; this is often called percent encoding) and then decode them to make them easier for humans to read. URL encoding is important to make sure links in your emails work—unencoded URLs can break. Another encoding format is base64, used for embedding image files in HTML and sending email attachments. 

Take a look at the escape and url_encode filters. Escape replaces special characters—in this case, quotation marks—with percent-encoded, URL-safe characters:

Code {{ “Have you read ‘How to Train Your Senior Dog’?” | escape }}
Output Have you read &#39;How to Train Your Senior Dog&#39;?

The URL_encode filter converts URL-unsafe characters with percent-encoded characters and converts spaces to a plus sign:

Code {{ “reach me at lee@email.com” | url_encode }}
Output reach+me+at+lee%40email.com

You can reverse URL encoding with the url_decode filter

Code {{ “reach+me+at+lee%40email.com” | url_decode }}
Output reach me at lee@email.com

The base64 filter (available in some Liquid flavors) can also be used to encode strings:

Code {{ “I love dogs.”’ | base64 }}
Output SSBsb3ZlIGRvZ3Mu

Hashing  

Hashing transforms a value in a way that guarantees its integrity. Stated another way, it allows us to check and see if two items are the same. Its most well-known application is passwords. 

Since storing passwords would present a huge security risk, typically passwords themselves are not stored in a database. Instead, they are hashed, and the resulting hash is stored. For example, when you create an account on a website, the password you set isn’t sent to the website—an algorithm transforms it into a hash, and that’s what’s actually stored. The next time you log in, the password you enter is hashed and compared to the stored hash of the password you set up initially—if they match, you entered the right password! 

Liquid offers several filters that can hash a value: sha1, sha256, and md5. Each represents a different hash algorithm. Here they are in action:

Code {{ “Customer.io” | md5 }}
Output d52b6a207bf5255c05b1d0056230617e
Code {{ “Customer.io” | sha1}}
Output c197ff0ae0a41983362f35ca972c544061c54d4c
Code {{ “Customer.io” | sha256 }}
Output 6dddb773238216bce273133bc3f6a12a824f41dd184d09452f05c7659dae7d57

Tricky terminology note: In Ruby (Liquid’s parent language), the word “hash” is also used to mean a collection of keys—the rough equivalent of a JavaScript object. See Advanced For Loops [link] for a brief discussion of hashes in that context.

Hashing in encryption schemes   

Encrypting transforms a value in a way that guarantees confidentiality. That is, access is restricted to authorized users. A cryptographic key is required to encrypt the value, and a different cryptographic key is required to decrypt it. (“Key” here means a cryptographic key, not a Liquid key.)

While we don’t actually use Liquid to encrypt data, some encryption schemes will use hashing to verify integrity as one of the many steps in the encryption process. Hash-based message authentication codes, or HMACs, include both a hash function and a secret cryptographic key. You’ll know when to use this type of hashing, because the instructions you’re following will explicitly state it is required—here’s an example about creating the signature needed to pass data to the Twitter API.  

Here’s a quick look at HMAC hash filters:

Code {{ “Customer.io” | hmac_sha1: “some_key” }}
Output 2bdf556c9a75766f258d1e2824f6d0e31d1beedc
Code {{ “Customer.io” | hmac_sha256: “some_key” }}
Output 6dddb773238216bce273133bc3f6a12a824f41dd184d09452f05c7659dae7d57

Those are just the basics of how encoding, hashing, and ASDSD are done using filters in Liquid. There’s a lot more to know, so start with this Auth0.com article for a deeper dive if you’ll be working with these filters frequently. 

Advanced Liquid

Just got here? This module is part of a full-length Liquid tutorial. Start from the beginning.  

In this module, we’ll cover:

  • Date, time, and localization

  • Whitespace control
  • Encoding, hashing, and encryption schemes

  • For loops
  • Using Liquid in Customer.io

Now that you’re familiar with Liquid’s three parts—keys, filters, and tags—and you can put them all together to create ultra-personalized content, we’ll dive into a few special topics. This section is an opportunity to get your feet wet in an environment more like what you’ll encounter in the wild world of Liquid!

Date, time, and localization

Marketing emails frequently work with dates and tailor content to recipients’ regions. For example, when a new customer makes a purchase, you might send a discount code that expires in 10 days. You might also convert times to a customer’s time zone and convert currencies and number formats (like 12,000.00 vs 12 000,00) based on a customer’s region.

Depending on the flavor of Liquid you’re using, you’ll likely have a variety of filters that address most or all of these needs. We’ll give you an overview of common scenarios, and then you can explore your Liquid flavor’s documentation to learn what your options are.

The date filter

The date filter converts a timestamp value to a readable format. Timestamps are characters or encoded data that identify a date and time (like when your customer created an account or made a purchase), sometimes down to fractions of a second. 

Quick sidebar: timestamps are commonly stored in one of two formats. The first is a Unix timestamp, in which time is expressed as the milliseconds that have passed since January 1, 1970. This type of value is a number (specifically, an integer). The second format commonly used for timestamps is ISO 8601—also known as Universal Time Code (UTC) format. This type of value is a string. The UTC format is handy if you need to represent a date before 1970 (like if you want to represent a birthdate for someone over 51!).

In either case, the output a timestamp value is not at all human-friendly to read. That’s where the date filter comes in! Here’s a simple example using a orders.order_placed_at key, in which the value of that key is 1625079104—a Unix timestamp.

Code {{ orders.order_placed_at | date: %D}}
Output 30/06/2021

The value of the orders.order_placed_at key is 1625079104—a Unix timestamp—and we’ve applied the date filter to output a date that’s legible to a reader. 

The date filter is extremely flexible, offering a wealth of options for how your date will be displayed. You just need to include formatting instructions in the filter. In the example above, the instructions are “%D”, which displays the date in DD/MM/YYYY format—which happens to be a common format for dates in European countries.

But maybe you’re emailing someone in the US! Or maybe you want to include the day of the week, or even very specific details about the time—it’s all possible! You can see a full list of available date format instructions here (scroll down to the section titled “rfc822(date)” to see the list)—or make your life a lot easier by using this STRFTIME resource to generate the formatting instructions you want.

Let’s apply a date filter with more complex formatting instructions:

Code {{ orders.order_placed_at | date: “%A, %b. %d, %Y %I:%M %p %Z” }}
Output Monday, Jun. 30, 2021 11:51 AM Pacific Daylight Time

Woo, that’s a super detailed output—all we have to do is include the formatting instructions in the order we want things displayed, with the punctuation and spaces we want. That’s important: put the punctuation and spaces in the code; they will appear exactly as entered in your output.

See for yourself how the magic is done. Head over to the STRFTIME resource and see if you can generate the code and recreate the output above. 

Fun fact: if your timestamp is in ISO 8601 instead of Unix, you can convert it by using “date: %s” in the code of your filter; check out the “seconds since 1970” button at the STRFTIME resource to see it happen.

Practice problem 

Now it’s your turn to practice with the date filter

Format your timestamp like this: Monday, 21 June 2021. Feel free to use the STRFTIME resource to compose your instructions for the date filter.

Choose the right Liquid code from the options below:

a: {{ orders.order_placed_at | date: %A, %e %B %Y}}

b: {{ orders.order_placed_at | date: %A %e %B %Y}}

c: {{ orders.order_placed_at | date: %a, %e %b %y}}

d: {{ orders.order_placed_at | %A, %e %B %Y}}

The correct answer is A! If you didn’t use the STRFTIME resource to compose your instructions for the date filter, go there now to experiment with the options.

Let’s run the code: 

Code {{ orders.order_placed_at | date: %A, %e %B %Y }}
Output Monday, 30 June 2021

Why don’t the other options work?

b. The comma after %A is missing. The output would be “Monday 21 June 2021”.

c. The letter case is wrong. Capitalization changes the meaning of this code: for example, %A is the full month name, and %a is the abbreviated month name. The output would be “Mon, 21 Jun 21”.

d. The “date:” portion of the filter is missing.

Using the now key

Liquid has another handy tool for outputting dates: the now key (depending on the flavor of Liquid you’re using, it might also be called the today key). The value of the now key is always the current date and time. Used with the date filter, “now” will output the current time, like this: 

Code {{ ‘now’ | date: “%A, %b. %d, %Y %I:%M %p %Z” }}
Output Monday, June 30, 2021 11:51 AM Pacific Daylight Time

Keep in mind that, as with all Liquid code, the value of the now key will be the time at which the code is actually rendered—for an email, that means the time your platform creates the email, not the time your reader opens the email. You might want to check out the Countdown Timers section of this tutorial on special content in HTML emails for more options.  

Other date and time filters

Some Liquid flavors have filters that add or subtract time increments to a given timestamp, which can be helpful for dynamically calculating new dates. Let’s say someone signed up for an annual subscription, and you want to let them know the date it will expire. Here’s how you can do that using Customer.io’s add_year filter:

Code {{ orders.order_placed_at | add_year: 1 }}
Output Monday, June 30, 2022 11:51 AM Pacific Daylight Time

Note that this particular filter requires that your timestamp is a Unix timestamp; check out the documentation for your flavor of Liquid for any necessary details like that for the filters you’re using. 

Localization tools

Many Liquid flavors have tools that convert currency, number format, or other elements to match the customer’s region. Using a localization filter or adding a localization parameter (essentially, extra instructions) to a filter is one way to accomplish this. 

Let’s use Customer.io’s currency filter as an example. Heads up: for this example, we’re using the assign tag to create a new key and value (that’s the first line of code below) to make it easier to see how this currency filter works. You learned in Intermediate Keys that you can use the assign tag to create keys and store their values right in your Liquid code.

Code {% assign my_money = “123456.78 ” %}
{{ my_money | currency }}
Output $123,456.78

The second line of code shows the currency filter. This filter defaults to US dollars, with a comma as the thousands separator and a period as the decimal separator. 

But what if you have a global audience? That’s where localization parameter comes in. Let’s use that same example, but this time a parameter to the currency filter indicating that our recipient is in France. Take a look at the second line of code: 

Code {% assign my_money = “123456.78 ” %}
{{  my_money | currency: “fr” }}
Output 123 456,78€

Now the currency displayed is euros, with a space as the thousands separator and a comma as the decimal separator—the correct currency and number format for that region. Et voila! 

Take some time to look through your Liquid flavor’s documentation to learn how to manage dates, times, currency, and other localization options! It’s a great opportunity to make your emails more personalized and more engaging—and that means more clicks.

Truthy and falsy

You may have been expecting Stephen Colbert in this section—nope, it’s still us, here with the truth about truthiness in Liquid. 

Liquid sometimes deals with non-boolean values (remember, boolean means true or false) in boolean contexts like conditional tags. That means a tag might have to evaluate a string, a number, an array, a nil value, or an EmptyDrop value to answer a true or false question. We can’t accurately say those values are true or false (because they aren’t boolean), so we call them truthy and falsy. 

Liquid considers all value types truthy except nil and false (for booleans). This can lead to some unexpected results. Let’s say we’re writing a personalized email salutation, and we want to include an alternate greeting if we don’t know the customer’s name. You could write the code like this:

{% if customer.name %}

Hi {{ customer.name }}

{% elsif %}

Hi new friend!

{% endif %}

It’s possible that this code will work just fine—if you don’t have a name for the customer, Liquid will output the second greeting. But if the customer.name key’s value is a special string type called an “empty string,” you’re going to get some funky results. Why? Because Liquid considers all strings—including empty ones—to be truthy. Here’s what the output would look like:

Hi

Not only are you missing the customer’s name, your alternate text hasn’t appeared either, because you actually do know the customer’s name! It’s… empty string.

To avoid the empty string problem, you can use blank. (You’ll remember this example from way back in Module 1!) Here’s how it looks:

{% if customer.name != blank %}

Hi {{ customer.name }}!

{% elsif %}

Hi friend!

{% endif %}

You’ve now got a solid basis for using tags along with filters and keys to do all kinds of cool things with Liquid! Now let’s get into some of the more complex issues in Module 6: Advanced Liquid.

Template tags

Template tags are a bit of an oddments drawer you can use to do a variety of things within your code. They can do things like prevent comments from being output, display raw Liquid code, and sometimes control output of template elements. Let’s take a look at the comment tag, as you’ll be reading and (and hopefully entering) comments in your code!

Code (key and tag){% comment %} 
I wrote the code this way for a good reason!
{% endcomment %}
Output 

The output is… nothing! That means your comments are visible to someone reading the Liquid code, but your customers won’t see a thing in the email. 

Practice problem: template tags

See if you can identify the correct way to use the comment tag.

Add the comment “Insert new product information here” to your code.

Select the right Liquid code from the options below:

a. {% comment %} 

Insert new product information here

b.{{ comment }}

Insert new product information here

{{ endcomment }}

c.{% comment %} 

Insert new product information here

{% endcomment %}

d. Insert new product information here

The correct answer is C!

Let’s run the code.

Code (key and tag){% comment %} 
Insert new product information here
{% endcomment %}
Output 

Why don’t the other options work?

a. Missing the closing section of the tag.

b. Uses double curly braces instead of paired curly brace and percentage signs to enclose the tag.

d. Tag is missing.

Operators and order of operations

We recapped the operators earlier; let’s look closer at some of the trickier ones. Most of the operators used with tags are fairly intuitive: == means equals, and contains means… well, that the string contains something! However, it’s helpful to have a deeper understanding of operators and how they work when using conditional tags.

Operators in conditional tags

Operators tell Liquid to do comparisons to determine whether conditions are met in conditional tags. Here’s a simple example using the if tag and the customer.purchased.most_recent key, the value of which is the last product the customer purchased:

{% if customer.purchased.most_recent == “leash” %}

Thank you for your recent purchase of a leash!

{% endif %}

To evaluate the first line of code, Liquid looks at the value of the customer.purchased.most_recent key and then compares it to “leash.” Since you’ve used the == operator, Liquid checks to see if they are the same. If they are, Liquid outputs your copy! If they aren’t, Liquid outputs nothing.

Using and or operators to do multiple comparisons

To do multiple comparisons, you can use the and and or operators, like this: 

{% if customer.purchased.most_recent == “leash” or “collar” %}

Now that your good boy has a {{ customer.purchased.most_recent }}, consider buying an ID tag!

{% endif %}

Here, Liquid is comparing the or statement with the key’s value; if they match, it will output the copy. If not, nothing happens. 

Liquid evaluates all and and or statements in pairs. With or, if either the left or the right side matches the key’s value, the condition is met. For and, the condition is not met unless both the left and the right side match the key’s value

This is simple and intuitive when you’re dealing with just one and or or operator. However, Liquid allows you to string together multiple pairs to create complex conditionals. 

Multiple “and” “or” operators

In tags with more than one and or or, Liquid reads the pairs from right to left. This can be some tricky business to remember—it’s the opposite of how Liquid reads filters, as well as and it’s not what we learned in math class about order of operations! 

Let’s look at an example. The customer.purchased key’s value is an array of a customer’s purchases: “leash”, “collar”. Here’s the code:

{% if customer.purchased == “bowl” or “leash” and “collar” %}

Click to see our selection of ID tags and bowl elevators!

{% endif %}

Liquid will read it like this: 

  1. Read the first pairs, starting on the right (leash, collar): Does the key’s value contain leash and collar? Yes.
  1. Go to the next pair to the left (bowl, leash): Does the key’s value contain bowl or leash? Yes.
  1. Are there any more and or operators? No.
  1. The condition is met because all the and or pairs matched with the key’s value.

Practice problem: multiple and and or pairs

Let’s practice using multiple and or statements. 

We’ll use the customer.purchased key. For this problem, its value is: “bowl elevator”, “vitamins”, “brush”, “shampoo”, “leash”. 

Look at the code below and choose the correct output from the two options. 

Code {% if customer.purchased contains “shampoo” and “brush” or “collar” and “vitamins” %}
Keep your pet healthy with gentle exercise!
{% endif %}
Output Copy is displayed.Copy is not displayed.

The correct answer is B! 

Let’s run the code (in slow motion):

  1. Read the first pair, starting from the right (collar, vitamins): Does the key’s value contain “collar” andvitamins”? No.
  1. Read the next pair (brush, collar): Does the key’s value contain brush or collar? Yes.
  1. Read the last pair (shampoo, brush): Does the key’s value contain shampoo or brush? Yes.
  1. The condition is not met because the first pair did not match the key’s value.

Variable tags

Variable tags assign a value to a new key for the purposes of a particular block of Liquid code. They are typically used in combination with filters and other tags. Here’s a very simple example of how the assign variable tag works:   

Code (key and tag){% assign favorite_food = “steak” %}
Your dog’s favorite food is {{ favorite_food }}.
Output Your dog’s favorite food is steak.

Practice problem: variable tags

Let’s practice creating keys with the assign tag

Assign a value of “yellow” to a new key, favorite_color. Then fill in the blank in this sentence with its value: Get a ___ leash for your hiking partner. 

Select the right Liquid code from the options below:

  1. {% assign favorite_color = “yellow” %}

Get a {{ favorite_color }} leash for your hiking partner.

  1. {% assign favorite_color = yellow %}

Get a {{ favorite_color }} leash for your hiking partner.

  1. {{ assign favorite_color = “yellow” }}

Get a {{ favorite_color }} leash for your hiking partner.

  1. {% favorite_color = “yellow” %}

Get a {{ favorite_color }} leash for your hiking partner.

The correct answer is A!

Let’s run the code :

Code (key and tag){% assign favorite_color = “yellow” %}
Get a {{ favorite_color }} leash for your hiking partner.
OutputGet a yellow leash for your hiking partner.

Why don’t the other options work?

b. The double quotes around yellow are missing. Strings must be surrounded by double quotes.

c. This part of the code is programming logic, not output, so it should be enclosed in pairs of curly braces and percentage signs. 

d. The word assign is missing in the first line of code.