Twig Access Array Index?

Viewed 67185

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]}}
3 Answers

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

Thats actually something what doesnt work for me when using Twig with shopware 6. I try to access an object like

{{ page.cart.lineItems.elements[0].quantity }}

what will lead into a parsing error of the Twig Template

I can use

{{ page.cart.lineItems.elements | first }}

to get the first Element, but dont know how i can then access a property of this first element

Related