ΓΓΓICK ΓΓΓICK - 20 days ago 6
Twig Question

Twig: get key of subarray without looping?

My Twig template is receiving an array that contains a path to an image file. It looks like this:

array:1 [
"path/to/images/images.jpg" => array:4 [
"name" => "image.jpg"
"type" => "image/jpeg"
"size" => 77789
"path" => "path/to/images/image.jpg"
]
]


You can see that the key of the subarray is being dynamically set to the actual path of the file. I can't access that array because I don't know that key beforehand. I know I can loop through the parent array to get any values from the subarray, but that seems messy. So my question is: is there any way, in Twig, that I can extract the key of the subarray (the path) without looping?

Answer

I'm not sure of the context surrounding the variable that you've shared, but...

Given a variable like the one in your question, I would access the path by utilizing the first filter in twig.

This assumes that your variable with the dynamically generated key is always being returned in the same, array-inside-a-one-item-array form:

{% set img = var | first %}
<img src="{{ img.path }}" />
// <img src="path/to/images/image.jpg" />
Comments