Twig

The flexible, fast, and secure
template engine for PHP

a Symfony Product
Docs Filters default
You are reading the documentation for Twig 3.x. Switch to the documentation for Twig 1.x, 2.x.

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

default

The default filter returns the passed default value if the value is undefined or empty, otherwise the value of the variable:

1
2
3
4
5
6
7
{{ var|default('var is not defined') }}

{{ user.name|default('name item on user is not defined') }}

{{ user['name']|default('name item on user is not defined') }}

{{ ''|default('passed var is empty')  }}

When using the default filter on an expression that uses variables in some method calls, be sure to use the default filter whenever a variable can be undefined:

1
{{ user.value(name|default('username'))|default('not defined') }}

Using the default filter on a boolean variable might trigger unexpected behavior, as false is treated as an empty value. Consider using ?? instead:

1
2
3
{% set value = false %}
{{ value|default(true) }} {# true #}
{{ value ?? true }} {# false #}

Note

Read the documentation for the defined and empty tests to learn more about their semantics.

Arguments

  • default: The default value