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

Community guidelines

Please keep discussions civil and on-topic. Repeated violations may lead to a temporary ban.

General

How can I get page images by index?

Started by Filippo Masoni 5 years ago · 7 replies · 1009 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

For the prettyness you might try {{ page.media.images|[1:1]|first }} 😃

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 %}
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

works without |

page.media.images[1:1]|first

and you're right, it's probably easier on the eyes

5 years ago

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 Jerry Hunt, 4 days ago
2 80 9 hours ago
General · by pamtbaau, 14 hours ago
1 51 14 hours ago
General · by Andy Miller, 1 day ago
0 44 1 day ago
General · by Marcel, 12 months ago
6 346 5 days ago
General · by Duc , 5 days ago
3 40 5 days ago