Pagination And Query In Hugo

Sep 8, 2017

Pagination

For layout pages like layouts/_default/list.html and layouts/_default/taxonomy.html, pagination take place by default.

You can overwrite the default pagination behaviour using the following code.

{{ $paginator := .Paginate (where .Site.Pages "Type" "tutorials") }}
{{ range .Paginator.Pages }}
  {{ .Title }} - {{ .Permalink }}
{{ end }}

If you have multiple AND conditions for your pagination query.

{{ $paginator := .Paginate (where (where .Site.Pages "Type" "tutorials") "IsPage" true) }}

Render Pagination Navigation

By default, _internal/pagination.html is used to render pagination navigation.

{{ template "_internal/pagination.html" . }}

You can render your own navigation creating your own Partial Templates. Create your template at layouts/partials/pagination.html.

{{ partial "pagination.html" . }}

The following pagination navigation template file is created using Bootstrap 4 classes.

{{ $pag := $.Paginator }}
{{ if gt $pag.TotalPages 1 }}
<nav aria-label="Page navigation">
    <ul class="pagination">
        {{ if $pag.HasPrev }}
        <li class="page-item"><a href="{{ $pag.Prev.URL }}" rel="prev" class="page-link">&laquo; Prev</a></li>
        {{ end }}
        {{ range $pag.Pagers }}
        {{ if eq . $pag }}
        <li class="page-item active"><a href="{{ .URL }}" class="page-link">{{ .PageNumber }}</a></li>
        {{ else }}
        <li class="page-item"><a href="{{ .URL }}" class="page-link">{{ .PageNumber }}</a></li>
        {{ end }}
        {{ end }}

        {{ if $pag.HasNext }}
        <li class="page-item"><a href="{{ $pag.Next.URL }}" rel="next" class="page-link">Next &raquo;</a></li>
        {{ end }}
    </ul>
</nav>
{{ end }}

NOTE: refer Hugo Smart Pagination Template for a smarter paging template.

Query

You can perform query to list certain pages without pagination.

For example, I want to list 5 tutorials on my first page. By default, the result is sorted by date in descending order.

{{ $pages := (where (where .Site.Pages "Type" "tutorials") "IsPage" true) }}
{{ range first 5 $pages }}
  {{ .Title }} - {{ .Permalink }}
{{ end }}

References

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.