Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig array access

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

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

Key "0" for 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's wrong with {{naziv[0]}} ?

like image 384
Xardas Avatar asked Jan 07 '13 15:01

Xardas


2 Answers

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

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

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

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

See the documentation.

like image 93
phpisuber01 Avatar answered Sep 20 '22 18:09

phpisuber01


Your array is not number indexed, thus naziv[0] is not defined. Access it as naziv.title.

like image 32
moonwave99 Avatar answered Sep 19 '22 18:09

moonwave99