Sort posts by weight then by title

By default, Hugo sorts pages by weight, then by date, then by link title, then by file path. I’m trying to change this to sort by weight then by title.

Here’s what I’ve tried:

In layouts/_default/list.html:

        {{ range .Pages.ByWeight .Pages.ByTitle }}

            {{ partial "postCard" . }}

        {{ end }}

This doesn’t work as .Pages.ByTitle is considered an argument of .Pages.ByWeight in this case.

Any ideas?

You cannot sort by multiple fields like you can with a SQL’s ORDER BY clause. You will need to group, then range through each group.

{{ range site.RegularPages.GroupBy "Weight" }}
  {{ range .Pages.ByTitle }}
    <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
  {{ end }}
{{ end }}

Assuming you don’t have any negative page weights, pages without weights will be at the top of the list.

3 Likes

Thanks for this @jmooring. This has the unintended consequence of changing the way posts are listed. It appears now that posts from sub-branches are listed on the root branch:
Before:

After:

I believe this is a consequence of a nested range. Is there another approach I could try?

I would need to see all of your templates to be sure. Please share a link to your project repository.

If I had to make an educated guess, try ranging over .Pages instead of site.RegularPages. The sample code I posted above was a generic example of how to group then range.

Apologies; I intended to include that link with my original post and forgot. However, using .Pages instead of site.RegularPages does the trick! Thanks so much for the help! I’ll accept this as the answer, but wonder if you might point me to the documentation where I can learn about the difference between .Pages and site.RegularPages as well.

https://gohugo.io/variables/site/#site-pages

1 Like

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