File: filter.rst

package info (click to toggle)
php-twig 2.14.3-1%2Bdeb11u2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,240 kB
  • sloc: php: 18,830; makefile: 215; sh: 42; python: 33
file content (59 lines) | stat: -rw-r--r-- 1,263 bytes parent folder | download
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
``filter``
==========

.. versionadded:: 2.10

    The ``filter`` filter was added in Twig 2.10.

The ``filter`` filter filters elements of a sequence or a mapping using an arrow
function. The arrow function receives the value of the sequence or mapping:

.. code-block:: twig

    {% set sizes = [34, 36, 38, 40, 42] %}

    {{ sizes|filter(v => v > 38)|join(', ') }}
    {# output 40, 42 #}

Combined with the ``for`` tag, it allows to filter the items to iterate over:

.. code-block:: twig

    {% for v in sizes|filter(v => v > 38) -%}
        {{ v }}
    {% endfor %}
    {# output 40 42 #}

It also works with mappings:

.. code-block:: twig

    {% set sizes = {
        xs: 34,
        s:  36,
        m:  38,
        l:  40,
        xl: 42,
    } %}

    {% for k, v in sizes|filter(v => v > 38) -%}
        {{ k }} = {{ v }}
    {% endfor %}
    {# output l = 40 xl = 42 #}

The arrow function also receives the key as a second argument:

.. code-block:: twig

    {% for k, v in sizes|filter((v, k) => v > 38 and k != "xl") -%}
        {{ k }} = {{ v }}
    {% endfor %}
    {# output l = 40 #}

Note that the arrow function has access to the current context.

Arguments
---------

* ``array``: The sequence or mapping
* ``arrow``: The arrow function