我有一个与使用 Twig 模板引擎处理数组相关的问题:我想在 Twig 中使用一个数组,但只显示从指定数组索引开始的数组中的数据。

在 PHP 中,我可以从数组的第二项开始,如下所示:

$alphabet = array("a","b","c","d");
for ($i = 1; $i < count($alphabet); $i++){
    echo($alphabet[$i]);
}

我怎样才能用 Twig 做类似的事情?

目前,我只能想出这个:
{% for letter in alphabet %}
{{ letter }}
{%endfor}

但结果显示“a,b,c,d”。

但我只想显示“b,c,d”。

这可能与 Twig 有关吗?

最佳答案

你会想要使用 slice ( documentation here ) 来做这样的事情:

{% for letter in alphabet[1:] %}
{{ letter }}
{% endfor %}

在上面的例子中,[1:] 本质上意味着:



查看 slice 过滤器的另一种方式是这样的:
[start:length]
  • start : 数组索引,从中开始
  • length :要显示多少数组
  • 关于php - 使用 Twig 从特定数组索引开始,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17115187/

    10-12 12:30
    查看更多