Files
liquid/documentation/basics/true-and-false.md
2014-07-23 09:43:56 -04:00

3.2 KiB
Raw Blame History

layout, title, nav
layout title nav
default Truthy and Falsy
group weight
Liquid Variables 6

Truthy and Falsy in Liquid

In programming, we describe “truthy” and “falsy” as anything that returns true or false, respectively, when used inside an if statement.

What is truthy?

All values in Liquid are truthy, with the exception of nil and false.

In the example below, the text “Tobi” is not a boolean, but it is truthy in a conditional:

{% highlight html %}{% raw %} {% assign tobi = 'Tobi' %} {% if tobi %} This will always be true. {% endif %} {% endraw %}{% endhighlight %}

Strings, even when empty, are truthy. The example below will result in empty HTML tags if settings.fp_heading is empty:

Input

{% highlight html %}{% raw %} {% if settings.fp_heading %}

{{ settings.fp_heading }}

{% endif %} {% endraw %}{% endhighlight %}

Output

{% highlight html %}{% raw %}

{% endraw %}{% endhighlight %}

To avoid this, you can check to see if the string is blank, as follows:

{% highlight html %}{% raw %} {% unless settings.fp_heading == blank %}

{{ settings.fp_heading }}

{% endunless %} {% endraw %}{% endhighlight %}

An EmptyDrop is also truthy. In the example below, if settings.page is an empty string or set to a hidden or deleted object, you will end up with an EmptyDrop. The result is an undesirable empty <div>:

Input

{% highlight html %}{% raw %} {% if pages[settings.page] %}
{{ pages[settings.page].content }}
{% endif %} {% endraw %}{% endhighlight %}

Output

{% highlight html %}{% raw %}
{% endraw %}{% endhighlight %}

What is falsy?

The only values that are falsy in Liquid are nil and false.

nil is returned when a Liquid object doesn't have anything to return. For example, if a collection doesn't have a collection image, collection.image will be set to nil. Since that is “falsy”, you can do this:

{% highlight html %}{% raw %} {% if collection.image %}

{% endif %} {% endraw %}{% endhighlight %}

The value false is returned through many Liquid object properties such as product.available.

Summary

The table below summarizes what is truthy or falsy in Liquid.

truthy falsy
true ×
false ×
nil ×
string ×
empty string ×
0 ×
1 or 2 or 3.14 ×
array ×
empty array ×
collection ×
collection with no products ×
page ×
EmptyDrop ×