Variables, assignments, and naming conventions

From previous lessons you have seen variables in Liquid. 

{% assign variable = "Joe Pichardo" %}

Variables are a way to save data. The way it is done in Liquid is to use the "assign" tag between these braces and percent signs {% %}.

You can still manipulate this data after it is assigned. Here we changed my name to John Doe instead.

{% assign variable = "Joe Pichardo" %}
{% assign variable = "John Doe" %}
{{ variable }}

The outcome:

John Doe

In my opinion, one of the most important thing to remember is to give your variable name meaning and purpose. Right now it is just "variable", which is bad practice. In this case, it should be "full_name". This gives our code readability and saves us time of giving us understanding of what the code is and does when we look back at what we have programmed. 

{% assign full_name = "Joe Pichardo" %}

I've used the underscore "_" to signify a space for two reasons. First, it is a practice that Shopify uses in their code, for example content_for_header, plus if you use a dash "-" the editor won't select the entire variable name on a double click (Just a nitpick for me). Second, you cannot have empty spaces in your variable name. You can try this next code example yourself. There will be no output because the "assign" chooses the last word, which would be "space", as the variable name.

{% assign test space = "Joe Pichardo" %}
{{ test space }}

If you were to use {{space}}, there would be an output of "Joe Pichardo", but this creates headaches in code readability, so just don't do this. The focus here is when assigning data to a variable give it a purposeful name.

As you may have noticed, when we assign a variable we use the double quotes to wrap the value. You can use single quotes and they will work the same way.

{% assign full_name = 'Joe Pichardo' %}

Sometimes you will have to assign bigger values to a variable. For such a situation, you can use the "capture" tag. It does the same thing as "assign", but it handles multi-line data with ease. For example, when saving an address:

{% capture address %}
Apple
One Apple Park Way
Cupertino, CA 95014
(408) 996–1010
{% endcapture %}

{{ address }}

We call on the variable the same way with double curly braces.

Joe Pichardo | Shopify Developer

About Joe Pichardo

Joe Pichardo is a Shopify Developer creating themes and apps to help other programmers succeed on the ecommerce platform.

Having trouble? Ask for help.