Access Twig Array

I am trying to print the value of a variable passed to a branch template. I am using this code:

{{ naziv[0] }} The index is 0 because the passed array has only one element. The mentioned code causes the following error:

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

but when i use for loop like this:

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

I get what I want.

What happened to {{naziv[0]}} ?

+4
source share
2 answers

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

You should access your array as follows: {{ naziv['title'] }} .

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

You can also use: {{ naziv.title }} .

See the documentation.

+12
source

Your array is not indexed by a number, so naziv[0] is undefined. Access it as naziv.title .

+5
source

All Articles