Filters
What’s a filter?
You already know that a key is a container for a value, like a customer’s name. Sometimes that’s all you need to personalize an email!
But you may also want to manipulate how keys are displayed to make your email better. To give a few examples, you might want to:
- capitalize a word (like a person’s name)
- calculate the end date of a free trial
- convert a timestamp to a date that’s easy on the eyes
That’s where Liquid filters come in—they change how values are displayed in emails. It’s teamwork time for Liquid components!
The capitalize filter is a great place to start. It’s just what it sounds like—it capitalizes the first letter of the key’s value when it’s displayed in your email.
Here’s our code and output again without a filter:
Hi {{ customer.first_name }},
Hi lee,
And here’s what happens when we apply the capitalize filter to our customer.first_name key:
Hi {{ customer.first_name | capitalize }},
Hi Lee,
There are many types of filters you can use to manipulate how the values of your keys are displayed—such as strip to take out extra whitespace and upcase to capitalize all the letters.
Practice problem
Your turn! Remember the extra spaces after Spot’s name in the first lesson in this module? Let’s fix them too, using the strip filter.
That’s not right; try again!
The right answer is C!
Let’s run the code and see what happens:
Hi {{ customer.first_name | capitalize }} (and {{ pet.pet_name | strip }})!
Hi Lee and Spot!
Now we’re getting somewhere! We’ve got a super-personalized email salutation that’s nicely formatted. Now let’s get totally clear on filter notation in Liquid.
Filter notation
Filters always go after the key, inside the double curly braces. Separate filters from the key with a pipe character, like this:
{{ key.key | filter }}
You can use as many filters as you like for each key. Liquid will apply the filters in order from left to right:
{{ key.key | filter | filter }}
Sometimes the order in which filters are listed makes no difference—like when you apply the capitalize and strip filters to the same key to capitalize a name and get rid of ugly whitespace. But as you’ll learn later (in the Intermediate Filters module), sometimes filters do more complex manipulations (like math calculations). In that situation, filter order matters a lot—so just file that nugget away in your brain for later!