Twig 数组访问数组、Twig

2023-09-07 00:25:31 作者:人缘好坏葬礼那天才知道

我正在尝试打印传递给 twig 模板的变量的值.我正在使用此代码:

I'm trying to print out value of the variable passed to the twig template. I'm using this code:

{{ naziv[0] }} 索引为 0,因为传递的数组只有一个元素.提到的代码产生以下错误:

{{ naziv[0] }} Index is 0 because passed array has only one element. Mentioned code produces following error:

键为title"的数组的键0"在...中不存在

Key "0" for array with keys "title" does not exist in...

但是当我像这样使用 for 循环时:

but when I use for loop like this:

{% for key,value in naziv %}
{{ value }}
{% endfor %}

我得到了我想要的.

{{naziv[0]}} 有什么问题?

推荐答案

基于array(1) { ["title"]=>的var_dump字符串(11)太空视觉"}

Based on the var_dump of array(1) { ["title"]=> string(11) "SpaceVision" }

您应该以这种方式访问​​您的数组:{{ naziv['title'] }}.

You should access your array in this way: {{ naziv['title'] }}.

数组的键是关联数组,而不是数字索引数组.这就是为什么你不能使用 naziv[0].

The key of your array is associative and not a numerically indexed array. That is why you cannot use naziv[0].

您也可以使用:{{ naziv.title }}.

请参阅文档.