How to use pagination variables across multiple blocks?

Hi there!

I’m trying to use bits from pagination in both the ‘main’ and ‘header’ blocks (I’m using the page number as a conditional to display a different header on pages that aren’t the first one). It looks like because of scope, I can’t set a $paginator variable with the paginator and use it in both places. I’m trying to give $.Scratch a try to get a global scope for it, but I can’t seem to get the pagniation into it. I tried:

{{ $.Scratch.Add "paginator" .Paginate (where .Data.Pages "Section" "posts") }}

And this results in the error:

<$.Scratch.Add>: wrong number of args for Add: want 2 got 3

So I tried to set the paginator to a variable first:

{{ $paginator := .Paginate (where .Data.Pages "Section" "posts") }}
{{ $.Scratch.Add "paginator" $paginator }}

But that gives this error:

<$.Scratch.Add>: error calling Add: Can’t apply the operator to the values

I’ll keep mucking around, but I figured that I could be missing a basic concept here.

Thank you!

It is important to understand that there is only one paginator instance per page. That means that you can do:

$pag := .Paginate (where .Data.Pages "Section" "posts")

And then later somewhere else in the same page template (can be a partial or whatever):

$pag := .Paginator

Those two will point to the exact same object (a pointer in the Go world).

The order is important in the above. If it is created, you cannot change it (with different where clause etc.)

Thank you, Bjørn, that helped a lot. That was one piece I was missing, and the other was that I needed to initialize the pagination within a block. First, I tried putting it outside, like:

{{ $paginator := .Paginate (where .Data.Pages "Section" "posts") }}
{{ define "header" }}

But when I switched it, it worked, even when I used the pagination in other blocks:

{{ define "header" }}
  {{ $paginator := .Paginate (where .Data.Pages "Section" "posts") }}

Thank you again!