Sorting ByLastmod + Pagination doesn't sort properly


I have a list section on my website with pagination, the first range is just .Paginate.Pages and it sorts the articles by the day I generate them, and I added a toggle to show another range that also has pagination but ByLastmod this time, using gitInfo.

The first range is sorting things okay: newer articles appear at the top and older articles the further you go down the pagination. But the ByLastmod doesn’t do that, articles seem to be sorted ByLastmod but only by paginator page, each page on the pagination is being sorted but it’s not “global”. It’s weird to explain but I think that’s what’s happening, if I remove the pagination it sorts the articles like I expect…

This is the bit of code that’s causing the issue:

{{ range (.Paginate .Pages).Pages.ByLastmod.Reverse }}
{{/*  {{ range .Pages.ByLastmod.Reverse }}  */}}
    <li class="text-flicker">
            <span class="post-time post-time-normal">{{ .Lastmod.Format "2006-01-02" }}:</span>
            <span class="post-time post-time-rel" style="display: none;"><script>document.write(getRelativeTimeString(new Date("{{ .Lastmod.Format `2006-01-02T15:04:05Z07:00` }}"), 'en-GB').padEnd(16, '.'))</script>:</span>
            &nbsp;<a class="white-color" href="{{ .Page.RelPermalink }}">{{ .Title | truncate 120 }}</a>
{{ end }}

I hope I was clear, thanks in advance

You need to filter/sort/group before you paginate.

{{ range (.Paginate .Pages.ByLastmod.Reverse).Pages }}

Hello thanks for your reply, I actually had already tried this and the way that it sorts the articles is even weirder, now it’s not even sorting them ByLastmod per page, it’s just random.

Here’s a list of things I tried with no luck apart from the first one:

{{ range (.Paginate .Pages).Pages }} {{/* sorts the default way and works with pagination */}}

{{ range (.Paginate .Pages).Pages.ByLastmod.Reverse }} {{/* sorts ByLastmod but by page, not globally  */}}
{{ range .Paginator.Pages.ByLastmod.Reverse }} {{/* same thing as above  */}}
{{ range (.Paginate .Pages.ByLastmod.Reverse).Pages }} {{/* sorting in a very weird way?? or maybe not at all? */}}
{{ range .Pages.ByLastmod.Reverse }} {{/* sorts okay but no pagination */}}

You are paginating twice within the same template. You can’t do that.

Once either .Paginator or .Paginate is called while generating a page, its result is cached, and any subsequent similar call will reuse the cached result. This means that any such calls which do not match the first one will not behave as written.

Ohh I see, I removed my first paginate call and now it’s sorting correctly, I really thought it would be a “legit” use case to call paginate twice in the same list page. I guess I’ll have to make another list page for my site then. Is doing what I’m doing ever coming to hugo?


No. You can paginate once per template.

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