Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``default`` |
| 2 | =========== |
| 3 | |
| 4 | The ``default`` filter returns the passed default value if the value is |
| 5 | undefined or empty, otherwise the value of the variable: |
| 6 | |
| 7 | .. code-block:: twig |
| 8 | |
| 9 | {{ var|default('var is not defined') }} |
| 10 | |
| 11 | {{ var.foo|default('foo item on var is not defined') }} |
| 12 | |
| 13 | {{ var['foo']|default('foo item on var is not defined') }} |
| 14 | |
| 15 | {{ ''|default('passed var is empty') }} |
| 16 | |
| 17 | When using the ``default`` filter on an expression that uses variables in some |
| 18 | method calls, be sure to use the ``default`` filter whenever a variable can be |
| 19 | undefined: |
| 20 | |
| 21 | .. code-block:: twig |
| 22 | |
| 23 | {{ var.method(foo|default('foo'))|default('foo') }} |
| 24 | |
| 25 | Using the ``default`` filter on a boolean variable might trigger unexpected behavior, as |
| 26 | ``false`` is treated as an empty value. Consider using ``??`` instead: |
| 27 | |
| 28 | .. code-block:: twig |
| 29 | |
| 30 | {% set foo = false %} |
| 31 | {{ foo|default(true) }} {# true #} |
| 32 | {{ foo ?? true }} {# false #} |
| 33 | |
| 34 | .. note:: |
| 35 | |
| 36 | Read the documentation for the :doc:`defined<../tests/defined>` and |
| 37 | :doc:`empty<../tests/empty>` tests to learn more about their semantics. |
| 38 | |
| 39 | Arguments |
| 40 | --------- |
| 41 | |
| 42 | * ``default``: The default value |