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