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]}}
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] }} .
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]}}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With