Strange "if" block + .Paginate behavior

Originally my list.html use .Scratch as follow:

{{if .IsHome}}
{{.Scratch.Set "Paginator" (.Paginate (where .Site.RegularPages "Type" "in" site.Params.mainSections))}}
{{else}}
{{.Scratch.Set "Paginator" .Paginator}}
{{end}}
{{$paginator:=(.Scratch.Get "Paginator")}}
{{range $paginator.Pages}}
{{.Title}}
{{end}}

After reading this https://gohugo.io/templates/introduction/#variables, I want to get rid of .Scratch and come up with method 1:

{{$paginator := .Paginator}}
{{if .IsHome}}
{{$paginator = .Paginate (where site.RegularPages "Type" "in" site.Params.mainSections)}}
{{end}}

But that doesn’t work as intended. The home page include pages from all sections instead of only the main.

So I come up with method 2:

{{$p := .Pages}}
{{if .IsHome}}
{{$p = where site.RegularPages "Type" "in" site.Params.mainSections}}
{{end}}
{{$paginator := .Paginate $p}}

It work this time.

Why method 1 does not work?

The paginator object for a given page is lazily created and only created once. We used to issue a warning in your situation, not sure why I removed that.

But what you need to do is:

{{ $paginator := "" }}
{if .IsHome}}
{{$paginator = .Paginate (where site.RegularPages "Type" "in" site.Params.mainSections)}}
{{ else }}
{{ $paginator = .Paginator }}
{{end}}
1 Like

oh, we just assign empty at the top declaration and do the actual assignment inside the “if” block?

1 Like

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