Nested Params sort

This question - Nested sorting for page resources got an answer requesting a repo share, and remains unresolved.

I have a simpler version of the question, and I can’t see that it needs a repo share, since it is a straightforward syntax question regarding the Hugo sort function.

Very simply, I have two params : ‘date’ and ‘votes’, set in the front matter of content files in the ‘post’ section. I want to sort them on a listing page by votes, and within that, by date.

So posts with these characteristics:

    • Post1 votes: 3 date: 2020:03:14
    • Post2 votes: 5 date 2020:06:22
    • Post3 votes: 3 date: 2020:09:02
    • Post4 votes: 7 date 2020:09:21
    • Post5 votes: 3 date: 2020:10:06
    • Post6 votes: 7 date 2020:11:12
    • Post7 votes: 3 date: 2020:12:17
    • Post8 votes: 5 date 2021:01:23

Will be listed as follows:

    • Post6 votes: 7 date 2020:11:12
    • Post4 votes: 7 date 2020:09:21
    • Post8 votes: 5 date 2021:01:23
    • Post2 votes: 5 date 2020:06:22
    • Post7 votes: 3 date: 2020:12:17
    • Post5 votes: 3 date: 2020:10:06
    • Post3 votes: 3 date: 2020:09:02
    • Post1 votes: 3 date: 2020:03:14

The form:

{{ range (.Paginate (sort .Pages “Params.votes” “desc”)).Pages }}

works to get the list sorted by votes, but there is nothing in the documentation to tell me how to introduce a secondary sort key.

Is this possible using the Hugo sort function?

If not, is there another way?

Thanks

Dil

You have to group, then sort each group.

{{ range .Site.RegularPages.GroupByParam "votes" }}
  {{ $votes := .Key }}
  {{ range .Pages.ByDate }}
    <h2>
      <a href="{{ .Permalink }}">{{ .Title }}</a> Votes: {{ $votes }} Date: {{ .Date.Format "2006-01-02" }}
    </h2>
  {{ end }}
{{ end }}

If you want to reverse the group or sort direction, use the .Reverse method.

{{ range (.Site.RegularPages.GroupByParam "votes").Reverse }}
  {{ $votes := .Key }}
  {{ range .Pages.ByDate }}
    <h2>
      <a href="{{ .Permalink }}">{{ .Title }}</a> Votes: {{ $votes }} Date: {{ .Date.Format "2006-01-02" }}
    </h2>
  {{ end }}
{{ end }}

To paginate:

{{ $p := slice }}
{{ range .Site.RegularPages.GroupByParam "votes" }}
  {{ range .Pages.ByDate }}
    {{ $p = $p | append . }}
  {{ end }}
{{ end }}


{{ range (.Paginate $p).Pages }}
  ...
{{ end }}
3 Likes

Thank you! Trying it now!

Dil

Works like a dream. Perfect. Thanks again.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.