slice

The slice filter extracts a portion of an array, hash or string.

{% for i in [1, 2, 3, 4, 5]|slice (1, 2) %}
    {{ i }}<br>
{% endfor %}

The above will output "2" and "3" on new lines.

{{ 'BranchCMS'|slice(2, 4) }}

Arguments

The slice filter has the following signature.

Argument Description
start

Required. The numeric position to start at in the slice.

If slicing an array the position starts at 0, with 0 being the first value of the array.

{% set new = [1, 2, 3, 4]|slice(2, 2) %}

The above will slice out [3, 4].

If slicing a string the position starts at 0, with 0 being the first character of the string.

{{ 'BranchCMS'|slice(0, 6) }}

The above will slice out 'Branch'

If the value is non-negative then the slice will start at that value. If the value is negative then the slice will start that far from the end of the variable.

{{ 'BranchCMS'|slice(-3) }}

The above will slice out 'CMS'.

length

The numeric size of the slice to retrieve. 

If the length value is not passed then the slice will go from the start position and continue to the end.

{{ 'BranchCMS'|slice(2) }}

The above will slice out 'ranchCMS'

If length is given and is positive then the slice will have up to that many values in it. If the variable is shorter than the length then only the available values will be sliced.

{% set num = [1, 2, 3, 4, 5]|slice(2, 10) %}

The above will slice out [3, 4, 5] even though 10 is the length.

If length is given and is negative then the slice will stop that many elements from the end of the variable.

{% set num = [1, 2, 3, 4, 5, 6, 7, 8, 9]|slice(2, -3) %}

The above will slice out [3, 4, 5, 6]

preserve_keys

Whether or not to preserve array keys. Only applies when the input is an array.

{% set new = array|slice(2, 3, true) %}

Examples

Slice an array to iterate over

{% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
    {# will iterate over 2 and 3 #}
{% endfor %}

Slice a string

{{ 'BranchCMS'|slice(8) }}

Using variables for start and length

{% set sliceStart = 2 %}
{% set sliceLength = 5 %}

{% set value = [1, 2, 3, 4, 5, 6, 7, 8, 9]|slice(sliceStart, sliceLength) %}

As an alternative you can use the [ ] syntax.

{% for i in [1, 2, 3, 4, 5][1, 2] %}
{% endfor %}

{{ 'BranchCMS'[5, 3] }}

You can omit the first artument, which is the same as passing 0

{{ 'BranchCMS'[:4] }}

The above will output 'Bran'

If you omit the last argument then the slice will contain everything from the start position to the end.

{{ 'BranchCMS'[6:] }}

The above will output 'chCMS'

< Back to the list of filters