Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig Access Array Index?

Tags:

twig

silex

Is it possible to directly access an array index from within a Twig template?

Here's my setup, using Silex:

return $app['twig']->render('template', array('numbers' => array('one', 'two', 'three'))); 

so can I do something like this?

{{numbers[0]}} 
like image 397
Adam Avatar asked Aug 07 '12 10:08

Adam


People also ask

How to access array index in twig?

Accessing array elements Twig as a parameter can receive array. To access a specific element of array you can use regular php array access bracket notation {{ array[key] }} .


2 Answers

Just before posting this I realized, that's exactly what you can do, but as I didn't find the answer anywhere in the docs or google (correct me if I'm wrong), I've posted this anyway.

{{numbers[0]}}  
like image 147
Adam Avatar answered Sep 20 '22 13:09

Adam


The answer of Adam, is correct, only to make it clear and improve, you can have access directly to array index

{{ myArray[0] }} 

if you need to access in a loop

{% set arrayOfItems = ['ZERO', 'ONE'] %} {% set myArray = ['APPLE', 'ORANGE'] %} {% for oneItem in arrayOfItems %}     <p>{{ oneItem }} equals {{ myArray[loop.index0] }}</p> {% endfor %} 

in this example I used an array inside a non related loop so the result is:

ZERO equals APPLE ONE equals ORANGE 
like image 41
Farzad.Kamali Avatar answered Sep 17 '22 13:09

Farzad.Kamali