Twig Access Array Index?
Asked Answered
H

4

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]}}
Homogenize answered 7/8, 2012 at 10:23 Comment(0)
H
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]}} 
Homogenize answered 7/8, 2012 at 10:23 Comment(2)
It does mention subscript access here under section "Variables" twig.sensiolabs.org/doc/templates.htmlMacmillan
@Macmillan So it does, I missed it.Homogenize
G
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
Gati answered 5/8, 2020 at 13:1 Comment(0)
Q
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

Quadriga answered 19/10, 2021 at 14:0 Comment(1)
If you have a new question, please ask it by clicking the Ask Question button. Include a link to this question if it helps provide context. - From ReviewStockton
R
0

The Answer from Adam is still correct and also works in Multidimensional Arrays. Just the comment with the Documentation Link is inccorect, which you find here as of 2024

{{numbers[x][y]}} 
Robichaud answered 13/2, 2024 at 14:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.