1

I'm having some difficulties using Twig.

When I call {{ dump(photos) }} I get:

array (size=4)
    0 => string 'gjdh15,jpg,200,200' (length=18)
    1 => string 'gjdh13,jpg,200,200' (length=18)
    2 => string 'gjdh12,jpg,200,200' (length=18)
    3 => string 'gjdh10,jpg,200,200' (length=18)

When I call {{ dump(photos[0]) }} I get:

string 'gjdh15,jpg,200,200' (length=18)

However when I call {{ dump(photos[1]) }} I get an exception :

Key "1" for array with keys "0" does not exist

When it clearly does.

Is there a special way to access array values using an index in Twig? (I can't use a loop).

3
  • I've reproduced your problem and it works for me. Maybe problem occurs in different line? Commented Jun 11, 2014 at 8:07
  • Where does photos come from? Is it really an array, or something that behaves like one? Commented Jun 11, 2014 at 8:56
  • @Sparkup What do you get if {{ dump(photos|keys) }}? You can also try {{ cycle(photos, 1) }} Commented Jun 11, 2014 at 14:51

1 Answer 1

1

To access a specific array value, you can use the attribute function, it works with both array and objects:

{{ attribute(photos, 1) }}

If the array key (or object attribute) may not exist, you can add the default filter to catch exceptions and print a fallback value.

{{ attribute(photos, 1)|default('No picture') }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.