slice

这个 slice 过滤器提取序列、映射或字符串的片段:

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 #}

可以对起始值和长度使用任何有效表达式:

1
2
3
{% for i in [1, 2, 3, 4, 5]|slice(start, length) %}
    {# ... #}
{% endfor %}

作为语法糖分,您还可以使用 [] 符号:

 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" #}

这个 slice 过滤器的作用是 array_slice 用于数组和 mb_substr 对于回退到的字符串 substr .

如果开始是非负的,序列将从变量的开始处开始。如果start为负数,序列将从远离变量结尾的地方开始。

如果长度给定并且是正的,那么序列中最多会有那么多元素。如果变量小于长度,则只存在可用的变量元素。如果length是给定的并且是负的,那么序列将从变量末尾停止那么多元素。如果省略它,那么序列将拥有从偏移量到变量结尾的所有内容。

注解

它还与实现 Traversable 接口。

争论

  • start :切片的开始
  • length :切片的大小
  • preserve_keys :是否保留密钥(当输入为数组时)