Sort by first element in front matter slice

I can’t seem to figure this one out. It might not even be possible in its current form.

I am trying to sort content in my template by the first element of a slice in my content’s front matter.

My content front matter:

title: Example
dates:
- 2019-05-30T14:30:00.000Z
- 2019-06-03T11:30:00.000Z
- 2019-06-03T11:30:00.000Z

I can’t seem to figure out how to sort by the first element in the dates slice.

Thanks for any help!

WHAT are you trying to sort? The three dates or three posts that are indicated by those dates?

Simple sorting would be

{{ range sort .Params.dates }}{{ . }} {{ end }}
{{ range sort .Params.dates "asc" }}{{ . }} {{ end }}
{{ range sort .Params.dates "desc" }}{{ . }} {{ end }}

but I am not sure what exactly you want to sort here.

Sorry for not being clear.

I am trying to sort all the content (of that type) by the first element of the dates slice.

There is a function called first that returns the first x slices. Use it with 1 and it should get you the first parameter.

The sort function then:

should run as follows (only logic, not working in real life):

{{ range $your-posts $their-first-slice "sortdir" }}

That seems to be quite complicated. I hope someone with more Go knowledge can help.

I was thinking about that as well, however the sort template function doesn’t support sorting by the provided value but only a key. And unfortunately it is not possible to specify an element of a slice by it’s index in the key.

I have extended hugo to support this, see pull request.

A post was split to a new topic: Sorting page collections by first element of a front matter slice