blob: ff38bbc9f43bfdbdf34bf073b4ea91b6663831bb [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001``slice``
2===========
3
4The ``slice`` filter extracts a slice of a sequence, a mapping, or a string:
5
6.. code-block:: twig
7
8 {% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
9 {# will iterate over 2 and 3 #}
10 {% endfor %}
11
12 {{ '12345'|slice(1, 2) }}
13
14 {# outputs 23 #}
15
16You can use any valid expression for both the start and the length:
17
18.. code-block:: twig
19
20 {% for i in [1, 2, 3, 4, 5]|slice(start, length) %}
21 {# ... #}
22 {% endfor %}
23
24As syntactic sugar, you can also use the ``[]`` notation:
25
26.. code-block:: twig
27
28 {% for i in [1, 2, 3, 4, 5][start:length] %}
29 {# ... #}
30 {% endfor %}
31
32 {{ '12345'[1:2] }} {# will display "23" #}
33
34 {# you can omit the first argument -- which is the same as 0 #}
35 {{ '12345'[:2] }} {# will display "12" #}
36
37 {# you can omit the last argument -- which will select everything till the end #}
38 {{ '12345'[2:] }} {# will display "345" #}
39
40The ``slice`` filter works as the `array_slice`_ PHP function for arrays and
41`mb_substr`_ for strings with a fallback to `substr`_.
42
43If the start is non-negative, the sequence will start at that start in the
44variable. If start is negative, the sequence will start that far from the end
45of the variable.
46
47If length is given and is positive, then the sequence will have up to that
48many elements in it. If the variable is shorter than the length, then only the
49available variable elements will be present. If length is given and is
50negative then the sequence will stop that many elements from the end of the
51variable. If it is omitted, then the sequence will have everything from offset
52up until the end of the variable.
53
54.. note::
55
56 It also works with objects implementing the `Traversable`_ interface.
57
58Arguments
59---------
60
61* ``start``: The start of the slice
62* ``length``: The size of the slice
63* ``preserve_keys``: Whether to preserve key or not (when the input is an array)
64
65.. _`Traversable`: https://secure.php.net/manual/en/class.traversable.php
66.. _`array_slice`: https://secure.php.net/array_slice
67.. _`mb_substr`: https://secure.php.net/mb-substr
68.. _`substr`: https://secure.php.net/substr