Truthy and Falsy
Alex Patton on Nov 3, 2021
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 }}
{% else %}
Hi 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 the How Liquid Works Lesson!) Here’s how it looks:
{% if customer.name != blank %}
Hi {{ customer.name }}
{% else %}
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.
Up Next: Advanced Liquid