slice

The slice filter extracts a slice of a sequence, a mapping, or a string:

スライス フィルターは、シーケンス、マッピング、または文字列のスライスを抽出します。
1
2
3
4
5
6
7
{% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
    {# will iterate over 2 and 3 #}
{% endfor %}

{{ '12345'|slice(1, 2) }}

{# outputs 23 #}

You can use any valid expression for both the start and the length:

開始と長さの両方に有効な式を使用できます。
1
2
3
{% for i in [1, 2, 3, 4, 5]|slice(start, length) %}
    {# ... #}
{% endfor %}

As syntactic sugar, you can also use the [] notation:

シンタックス シュガーとして、[] 表記も使用できます。
1
2
3
4
5
6
7
8
9
10
11
{% for i in [1, 2, 3, 4, 5][start:length] %}
    {# ... #}
{% endfor %}

{{ '12345'[1:2] }} {# will display "23" #}

{# you can omit the first argument -- which is the same as 0 #}
{{ '12345'[:2] }} {# will display "12" #}

{# you can omit the last argument -- which will select everything till the end #}
{{ '12345'[2:] }} {# will display "345" #}

The slice filter works as the array_slice PHP function for arrays and mb_substr for strings with a fallback to substr.

スライス フィルターは、配列の場合は array_slice PHP 関数として機能し、文字列の場合は mb_substr として機能し、substr にフォールバックします。

If the start is non-negative, the sequence will start at that start in the variable. If start is negative, the sequence will start that far from the end of the variable.

start が負でない場合、シーケンスは変数のその start から開始されます。 start が負の場合、シーケンスは変数の終わりから遠く離れて開始されます。

If length is given and is positive, then the sequence will have up to that many elements in it. If the variable is shorter than the length, then only the available variable elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the variable. If it is omitted, then the sequence will have everything from offset up until the end of the variable.

length が指定され、正の場合、シーケンスには最大でその数の要素が含まれます。変数が長さよりも短い場合、使用可能な変数要素のみが存在します。 length が指定され、負の場合、シーケンスは変数の末尾からその数の要素を停止します。省略した場合、シーケンスには、offsetup から変数の末尾までのすべてが含まれます。

Note

ノート

It also works with objects implementing the Traversable interface.

また、Traversable インターフェースを実装するオブジェクトでも機能します。

Arguments

  • start: The start of the slice
    start: スライスの開始
  • length: The size of the slice
    length:スライスのサイズ
  • preserve_keys: Whether to preserve key or not (when the input is an array)
    preserve_keys: キーを保持するかどうか (入力が配列の場合)