Sort page media?

How do I sort media files uploaded to my page? I couldn’t find any documentation on that.

By default, they’re sorted by filename it seems, both in the Admin Panel (where it makes little sense) and when querying page.media.images in Twig.

I’d like to sort them by (upload) date, as you’d expect in a CMS.

Depending on what you need, you could use a list of images instead of the page media field.

It will allow you to order the images however you want. Here’s what I use for the blueprint.

header.imageList:
   name: imageList
   type: list
   style: vertical
   label: Images
   fields:
      .image:
         type: file
         label: Image
         multiple: false
         destination: 'path/to/folder'
         accept:
            - image/*

And then to render them, here is the twig code.

{% for imageListItem in page.header.imageList %}
   {% for image in imageListItem %} 
      <img src='{{ image.path }}' />
   {% endfor %}
{% endfor %}

Hope that helps!

Wow, that looks very intriguing! I’m not well versed with Grav yet so bear with me. The header.imageList code would go into a blueprint file, e.g. mytheme/blueprints/gallery.yaml (if gallery.md/html.twig were the page I use this on), yes?

And how come there are two nested loops? I would have expected a singular array structure.

Yeah, it takes a bit to get used to, but it is awesome to use.

But, to answer your questions, the blueprints is correct. I believe I used this when I was learning about blueprints.

As for the template file, you would want it nested under mytheme/templates/gallery.html.twig

And the only reason I have the nested loop is I couldn’t find a way to grab the data without it. I think it has to do with the structure of how Grav saves the content. It ends up looking like this when you use the file field for your images.

imageField:
   /path/to/file.jpg:
      name: file.jpg
      type: image/jpeg
      size: 4048
      path: path/to/file.jpg

so I tried

{% for imageListItem in page.header.imageList %}
      <img src='{{ imageListItem[0].path }}' />
{% endfor %}

and

{% for imageListItem in page.header.imageList %}
      <img src='{{ imageListItem }}' />
{% endfor %} 

but no luck.

Maybe someone at Grav can comment on getting around that?