Truthy and Falsy
In Liquid, truthy and falsy values are essential for determining the outcome of conditional statements. This document provides an overview of what truthy and falsy values are and how they work in Coco templates.
1. Truthy Values
A truthy value is any value that evaluates to true in a conditional statement. In Liquid, all values are considered truthy except for those explicitly defined as falsy.
Examples of truthy values:
Non-empty strings:
"hello"
Numbers other than zero:
42
Non-empty arrays:
[1, 2, 3]
Non-empty hashes:
{"key": "value"}
Example usage:
In this example, if product.name
contains a non-empty string, it is considered truthy, and the title is displayed.
2. Falsy Values
A falsy value is any value that evaluates to false in a conditional statement. In Liquid, there are only two falsy values: false
and nil
.
Examples of falsy values:
false
: Represents a boolean false value.nil
: Represents an undefined or empty value.
Example usage:
In this example, if product.available
is false
, it is considered falsy, and "Out of stock" is displayed.
3. Coercion
When using non-boolean values in a conditional statement, Liquid will automatically coerce the value to its boolean equivalent. This means that truthy values will be treated as true and falsy values as false.
Example:
In this example, if product.tags
is an empty array or nil
, it is considered falsy, and the tags will not be displayed.
Summary
Understanding truthy and falsy values in Liquid is essential for creating accurate and efficient conditional statements. By recognizing which values are considered truthy or falsy, you can control the flow of your templates and display content only when certain conditions are met. This helps in creating responsive and dynamic themes that adapt to various scenarios and data inputs.
Last updated