Hugo Paginator Pitfall

Wow - If you are not careful with the Hugo Paginator feature, you can run into some nasty pitfalls...

Home / Posts / Hugo Paginator Pitfall
Auvik - Monitor Everything on your Network

Today I work on a theme for my Blog and optimized some Meta & Title information on the various Pages. Part of my new custom Hugo Theme was inspired by the current used Theme of this Blog.

The Pagination takes care of splitting the posts into different pages, but there is one important caveat you have to understand.

If you call .Paginator or .Paginate multiple times on the same page, you should ensure all the calls are identical. 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.

Like all the tech people out there, I would never read a documentation for something simple as a Paginator, right? But that was my downfall…

Reading Docs?!

Due to a lack of understanding of the features, I had many calls to the .Paginator, but not all where filtered in the same way.

This was the most basic one.

{{ if .Paginator }}
    {{ if .Paginator.HasPrev }}
        <!-- Add page number-->
        {{ $description = printf "%s - Page #%v" $description .Paginator.PageNumber }}
    {{ end }} 
{{ end }}

Others first applied some filtering, before using the .Paginator object itself.

    {{ $pages := where site.RegularPages "Type" "in" site.Params.mainSections }}
    {{ $notHidden := where .Pages "Params.hidden" "!=" true }}
    {{ $pag := .Paginate ($notHidden) }}

What in the end then matters is the order in which you call them. Before the first call to the .Paginator happens, you need to apply all the filtering through the .Paginate call. If you don’t do that and first use directly the .Paginator, then all parameters you pass to .Paginate later on, are ignored.

Lesson learned :)

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy