Answering the Questions Straight‑Up
1. Suppress pagination when the filter yields no items.
{{ if gt .Paginator.TotalPages 0 }}
{{ end }}
When the filtered collection is empty, .Paginator.TotalPages evaluates to 0. Wrapping the paginator block in this if prevents any links from being rendered, avoiding broken navigation.
2. Can .Where be applied to a slice before .Paginate?
Hugo’s .Where is a method on PageCollection objects only. It cannot be chained directly on a plain Go slice. To filter a slice you must either:
- Convert the slice to a PageCollection first, e.g.
.Pages.ByPublishDate or .Site.RegularPages, then apply .Where and finally .Paginate.
- Iterate over the slice with
range and apply an if test inside the loop, collecting the results into a new slice for manual pagination logic.
Example using a PageCollection:
{{ $filtered := .Site.RegularPages.ByPublishDate | where "Draft" false }}
{{ $paginator := $filtered | paginate 10 }}
Attempting slice | where … will produce a template error or be silently ignored.
3. Accessing the current page number inside a partial without leaking parent state.
Pass the paginator explicitly to the partial:
{{ partial "paginator.html" .Paginator }}
Inside paginator.html you can then use .PageNumber, .TotalPages, etc., safely isolated from the parent page’s context. If the partial also needs the original page data, pass it as a second argument using a map:
{{ partial "paginator.html" (dict "Paginator" .Paginator "Page" .) }}
Inside the partial:
{{ with .Paginator }}
Current: {{ .PageNumber }} of {{ .TotalPages }}
{{ end }}
Using this pattern keeps the paginator state local to the partial.
Practical Verification Steps (Hugo 0.124+)
- Create a list page that gathers pages into a slice:
{{ $list := .Pages }}.
- Filter using a PageCollection:
{{ $filtered := $list | where "Draft" false }}.
- Paginate:
{{ $paginator := $filtered | paginate 5 }}.
- Wrap the paginator block:
{{ if gt $paginator.TotalPages 0 }} … {{ end }}.
- Render the paginator inside a partial:
{{ partial "paginator.html" $paginator }} and confirm that .PageNumber displays correctly.
After generating the site, inspect the public folder: pagination controls should appear only when there are items to show, and links should point to valid pages.
What We Still Need to Know
If you are working with a Hugo version earlier than 0.124, the behavior of .Where and .Paginate may differ. Knowing your exact Hugo version will ensure the recommendations above apply without modification.