Truthy and falsy
Like most computer languages, Twig supports boolean data types and so everything has an inherent boolean value, known as truthy and falsy.
Even though an attribute/object may not be boolean it will still be truthy in a conditional.
For example,
{% if product.description %} <div> {{ product.description|raw }} </div> {% endif %}
returns...
<div> <p>These nike air max trainers are great.</p> </div>
As long as a product description is set.
Checking whether an attribute/object is truthy can avoid empty HTML tags.
The rules to determine if an expression is
true
or false
are the same as in PHP; here are the edge case rules:
empty string | false |
numeric zero | false |
whitespace-only string | true |
empty array | false |
null | false |
non-empty array | true |
object | true |