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:

{% assign my_variable = "Good dog!" -%}{{ my_variable }}
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!

Up Next: Advanced Liquid – Encoding, Hashing, and Encryption Schemes