Skip to content
Grav 2.0 is officially stable. Read the announcement →
General

How can I get page images by index?

Started by Filippo Masoni 5 years ago · 7 replies · 1154 views
5 years ago

I've been using page.media.images|first and |last for a while, but I'd like to know how to get the images in the middle of the array.

page.media.images[1] and page.media.images.1 don't work even though it should be the way to get the second value of the array.

5 years ago

If you were to dump(page.media.images), you'd notice the keys aren't numeric, but rather a file names. So you can access your image object like page.media.images['filename.jpeg']. Having this in mind, you could get a second image by using slice() maybe(?) to first get a key you need and then with that key follow the previous example to get the object itself

There might be a better way though, which I can't think of right now 😅

👍 1
5 years ago

Yes I know I can get the image with its filename, but it's not practical for a template to be used with the admin, image names can change, while it's very practical to change the order of the media.

I tried slice() function and ended up using:
page.media.images|slice(1,1)|first
it's not pretty but it works. I just wish they mentioned it in the documentation, since they have |first and |last they might as well tell as the best way to get the others.

5 years ago

@filo91, I think I find the following easier on the eyes...

Not sure what the use-case is, but the index is probably not a constant.

TWIG
{% set keys = page.media.images | keys %}
{% set index = ... %}

{{ page.media.images[keys[index]] | raw }}

Or maybe, depending on the use-case:

TWIG
{% for key, image in page.media.images %}
  {{ image | raw }}
{% endfor %}
1 reply
last edited 04/08/21 by pamtbaau
5 years ago

Was also thinking about the keys, but somehow then it just slipped :D Much simpler than slicing :)

5 years ago pamtbaau @filo91, I think I find the following easier on the eyes... Not sure what the use-case is…

Thank you, I haven't thought of that and it's definitely helpful for other situations.

For what I need right now, it's much simpler the one line of code, since I'm actually inside a for loop dealing with child images and I'm also applying multiple media actions to multiple images. I don't want the code to become too long and hard to read, so [1:1] is perfect

Suggested topics

Topic Participants Replies Views Activity
General · by jean-louis67, 3 weeks ago
2 308 3 weeks ago
General · by Andy Miller, 3 weeks ago
0 310 3 weeks ago
General · by Veehem, 4 weeks ago
0 263 4 weeks ago
General · by milkboy, 4 weeks ago
0 264 4 weeks ago
General · by ian russell, 1 month ago
2 335 1 month ago