File: default.rst

package info (click to toggle)
php-twig 3.5.1-1%2Bdeb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 4,560 kB
  • sloc: php: 17,829; makefile: 106; sh: 42
file content (42 lines) | stat: -rw-r--r-- 1,143 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
``default``
===========

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

.. code-block:: twig

    {{ var|default('var is not defined') }}

    {{ var.foo|default('foo item on var is not defined') }}

    {{ var['foo']|default('foo item on var 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:

.. code-block:: twig

    {{ var.method(foo|default('foo'))|default('foo') }}
    
Using the ``default`` filter on a boolean variable might trigger unexpected behavior, as
``false`` is treated as an empty value. Consider using ``??`` instead:

.. code-block:: twig

    {% set foo = false %}
    {{ foo|default(true) }} {# true #}
    {{ foo ?? true }} {# false #}

.. note::

    Read the documentation for the :doc:`defined<../tests/defined>` and
    :doc:`empty<../tests/empty>` tests to learn more about their semantics.

Arguments
---------

* ``default``: The default value