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:   

{% assign favorite_food = "steak" %}
Your dog’s favorite food is {{ favorite_food }}.
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:

That’s not right; try again!

The correct answer is A!

Let’s run the code:

{% assign favorite_color = "yellow" %}
Get a {{ favorite_color }} leash for your hiking partner.
Get 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.

Up Next: Intermediate Tags – Template Tags