How can I get page images by index?

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.

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 :sweat_smile:

1 Like

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.

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

@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.

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

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

Or maybe, depending on the use-case:

{% for key, image in page.media.images %}
  {{ image | raw }}
{% endfor %}

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

works without |

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

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

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