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 #}
您可以对 start 和 length 使用任何有效的表达式
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 12 13 14
{% 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" #}
{# you can use a negative value -- for example to remove characters at the end #}
{{ '12345'[:-2] }} {# will display "123" #}
slice
过滤器的工作方式类似于数组的 array_slice PHP 函数,以及字符串的 mb_substr,并回退到 substr。
如果 start 是非负数,序列将从变量中的该 start 位置开始。如果 start 是负数,序列将从变量末尾的那个位置开始。
如果给出了 length 并且是正数,则序列最多将包含那么多元素。如果变量比 length 短,则只会显示可用的变量元素。如果给出了 length 并且是负数,则序列将在变量末尾的那个位置停止。如果省略,则序列将包含从 offset 到变量末尾的所有内容。
参数 preserve_keys
用于在循环期间重置索引。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
{% for key, value in [1, 2, 3, 4, 5]|slice(1, 2, true) %}
{{ key }} - {{ value }}
{% endfor %}
{# output
1 - 2
2 - 3
#}
{% for key, value in [1, 2, 3, 4, 5]|slice(1, 2) %}
{{ key }} - {{ value }}
{% endfor %}
{# output
0 - 2
1 - 3
#}
注意
它也适用于实现 Traversable 接口的对象。
参数
start
:切片的开始位置length
:切片的大小preserve_keys
:是否保留键(当输入是数组时),默认值是false
。