5 The ``slice`` filter was added in Twig 1.6.
7 The ``slice`` filter extracts a slice of a sequence, a mapping, or a string:
11 {% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
12 {# will iterate over 2 and 3 #}
15 {{ '12345'|slice(1, 2) }}
19 You can use any valid expression for both the start and the length:
23 {% for i in [1, 2, 3, 4, 5]|slice(start, length) %}
27 As syntactic sugar, you can also use the ``[]`` notation:
31 {% for i in [1, 2, 3, 4, 5][start:length] %}
35 {{ '12345'[1:2] }} {# will display "23" #}
37 {# you can omit the first argument -- which is the same as 0 #}
38 {{ '12345'[:2] }} {# will display "12" #}
40 {# you can omit the last argument -- which will select everything till the end #}
41 {{ '12345'[2:] }} {# will display "345" #}
43 The ``slice`` filter works as the `array_slice`_ PHP function for arrays and
44 `mb_substr`_ for strings with a fallback to `substr`_.
46 If the start is non-negative, the sequence will start at that start in the
47 variable. If start is negative, the sequence will start that far from the end
50 If length is given and is positive, then the sequence will have up to that
51 many elements in it. If the variable is shorter than the length, then only the
52 available variable elements will be present. If length is given and is
53 negative then the sequence will stop that many elements from the end of the
54 variable. If it is omitted, then the sequence will have everything from offset
55 up until the end of the variable.
59 It also works with objects implementing the `Traversable`_ interface.
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)
68 .. _`Traversable`: http://php.net/manual/en/class.traversable.php
69 .. _`array_slice`: http://php.net/array_slice
70 .. _`mb_substr` : http://php.net/mb-substr
71 .. _`substr`: http://php.net/substr