Search code examples
hugogo-templateshugo-theme

Pagination in hugo is not working as expected


I only want 5 post summaries to be displayed, per page, in my hugo theme

In my config.toml file I have placed the following value:

pagination = 5

My themes/<theme_name>/layouts/_default/list.html looks like this:

{{ define "main" }}
<div class="container">
<h1>{{ .Title }}</h1>
{{ range .Paginator.Pages.ByPublishDate.Reverse }}
<p>
<h3><a class="title" href="{{ .RelPermalink }}">{{ .Title }}</a></h3>
{{ partial "metadata.html" . }}
<p>{{ .Summary }}</p>
</p>
<a href="{{ .RelPermalink }}" className='text-decoration-none'><button type="button" class="btn btn-outline-danger">Read More</button></a>
{{ end }}
{{ template "_internal/pagination.html" . }}
</div>
{{ end }}

Which from everything I've read, including the docs, should work

However this has no effect on my posts page where the list of posts is displayed. I have 6 posts currently, and all posts are listed on the same page, with no pagination settings displayed. There are no errors returned by when doing a hugo server -D

I have tried to remove the .ByPublishDate.Reverse from the range value, but that also has no effect

I believe I have missed something fundamental, but I'm not sure where to look next. Any help would be appreciated.


Solution

  • You need to make sure that your list.html template is using the .Paginate function to actually paginate your posts.

    Replace your {{ range .Paginator.Pages.ByPublishDate.Reverse }} line with the following:

    {{ range (.Paginate (where .Data.Pages "Type" "post")).Pages }}
    

    This will use the .Paginate function to paginate only the pages of type post (which should include your blog posts), and then loop through each page of posts using the .Pages function.

    Additionally, you may want to modify your {{ template "_internal/pagination.html" . }} line to include some styling and/or text to make it clear that pagination is in effect.

    Example:

    <div class="pagination">
      {{ if .Paginator.HasPrev }}
        <a href="{{ .Paginator.Prev.URL }}">← Newer Posts</a>
      {{ end }}
      {{ if .Paginator.HasNext }}
        <a href="{{ .Paginator.Next.URL }}">Older Posts →</a>
      {{ end }}
    </div>