How do I sort by Weight then Title?

Nearly all my content posts have weight="", but a few have weight="1".

I would like to order these posts in the order: ByWeight followed by ByTitle.

To get all posts listed in alphabetical order:

{{range .Pages.ByTitle}}

To get all posts listed by weight:

{{range .Pages.ByWeight}}

But how do I combine these two ordering functions? Something like this does not work as the content gets order by the last parameter ByTitle.

{{range .Pages.ByWeight.ByTitle}}

Any suggestions?

I read somewhere on here that it sorts by default by weight then title, but did you try nesting the ranges?

The default sort in Hugo is:

  • Weight (if set)
  • LinkTitle or Title

So, I would expect the “{{range .Pages}}” to work work for you.

1 Like

Thanks for helping out.

I’ve tried doing {{range .Pages}} but this doesn’t work as the sort order becomes:

  • Weight
  • Date

I’ve browsed through the docs and it says that the default sort order is:

Weight > Date > LinkTitle > FilePath

Which corresponds to what’s happening when I order my posts. Any other suggestions I can try?

Just bumping this thread to see if I can get some help.

I’m not sure if (Hu)go template sort uses a stable sorting algorithm, but if it does, maybe sorting them manually (in backwards order) could work:

{{ range sort (.Pages.ByTitle "Weight" "desc") }}

Other possible approach would be to group and then sort:

{{ range .Pages.GroupBy "Weight" "desc" }}
  {{ range .Pages.ByTitle }} / or maybe {{ range sort .Pages "Title" }}

(grouping docs)

1 Like

@madispe Many thanks for helping out. :1st_place_medal:

I got it to work by using your second approach:

  {{range .Pages.GroupBy "Weight" "desc"}}
  {{range .Pages.ByTitle}}