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.

Archive

Sort page media?

Started by Muut Archive 9 years ago · 3 replies · 2178 views
9 years ago

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.

9 years ago

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.

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

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

Hope that helps!

9 years ago

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.

9 years ago

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.

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

so I tried

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

and

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

but no luck.

Maybe someone at Grav can comment on getting around that?

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1280 9 years ago
Archive · by Muut Archive, 9 years ago
2 888 9 years ago
Archive · by Muut Archive, 9 years ago
2 4017 9 years ago
Archive · by Muut Archive, 9 years ago
1 2892 9 years ago
Archive · by Muut Archive, 9 years ago
3 1077 9 years ago