Truthy and Falsy
In Twig, as in many programming languages, values are often evaluated in a boolean context, meaning they are interpreted as either true
or false
. This concept is essential for controlling the flow of templates through conditionals and loops.
What is Truthy?
In Twig, a value is considered "truthy" if it evaluates to true
in a boolean context. These values include:
true
- Any non-empty string, such as
"hello"
or"0"
- Any non-zero number, such as
1
,-1
, or3.14
- Any non-empty array or object
Examples of Truthy Values:
{% if "hello" %}
This will be displayed.
{% endif %}
{% if 42 %}
This will also be displayed.
{% endif %}
What is Falsy?
A value is considered "falsy" if it evaluates to false
in a boolean context. These values include:
false
null
- An empty string
""
- The number
0
(zero) - An empty array
[]
or empty object
Examples of Falsy Values:
{% if "" %}
This will NOT be displayed.
{% endif %}
{% if 0 %}
This will NOT be displayed either.
{% endif %}
Using Truthy and Falsy in Conditionals
Understanding truthy and falsy values is particularly important when using in Twig templates. This allows you to perform actions based on whether a value exists, whether it's empty, or if it meets certain criteria.
{% if global.customer.first_name %}
Hello, {{ global.customer.first_name }}!
{% else %}
Hello!
{% endif %}
In this example, if global.customer.first_name
is an empty string (falsy), the template will output "Hello!".