47

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]}}
Adam
  • 5,091
  • 5
  • 32
  • 49

3 Answers3

77

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]}} 
Adam
  • 5,091
  • 5
  • 32
  • 49
3

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
D. Schreier
  • 1,700
  • 1
  • 22
  • 34
Farzad.Kamali
  • 553
  • 4
  • 10
2

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

samjaona
  • 46
  • 2
  • If you have a new question, please ask it by clicking the [Ask Question](https://stackoverflow.com/questions/ask) button. Include a link to this question if it helps provide context. - [From Review](/review/late-answers/30119811) – Tom Oct 19 '21 at 16:50