What is the best way to repeatedly get X record from Y .Pages?

After a post on recursion it got me rethinking how I do my current slapdash process to create rows of .Pages to pass to partials and whether there is a better way to chunk my .Pages (Y) collection into sections of X(in this case 4) . Recursion would be definitely be ideal.

Since I was more determined to get a frame up I didn’t dwell on the “best way” like I am now and just slapped something together to get it working. I used to do something like this earlier(no guarantee it is working code) but have since moved on to using .Paginator which is more concise and performs better with hundreds of posts.


{{$sitePages := where .Site.RegularPages ".Date.Year" "ge" 2021) }}
{{$passPages := ""}}
{{$count := div (len $sitePages) 4 }}
{{range $index := (seq 0 $count)}}
  {{ range $topics := first 4 (after (mul $index  4) $sitePages)  }}
    {{$passPages = $passPages | append $topics }}
  {{end}}
  {{ partial "archive/archrow.html" (dict "context" . "arch_pages" $passPages "break_at" 2) }}
{{end}}

Now I use a .Paginator version which is faster, more concise/intelligible despite being an abuse/misuse/pick-your-term of .Paginator in my opinion (and according to the number of paginated pages it creates in my hugo server log)

{{$paginator = .Paginate (where .Site.RegularPages ".Date.Year" "ge" 2021) 4}} 
{{range $d := $paginator.Pagers}}
    {{ partial "archive/archrow.html" (dict "context" . "arch_pages" .Pages "break_at" 2) }}
{{end}}

But as with all things, and the fact this was just a quick coding build, there must be…must be a better way and I’m hoping for a process that does this recursively. All pointers/things to read appreciated. And hopefully it’s not something I skipped over in the Docs.

Edit: quick side note the .Paginate I did above doesn’t actually create URL references without applying a template so the server will show that there are X paginated pages when in reality they do not actually resolve to any (/1 , /2, etc)

{{ $groupSize := 4 }}
{{ $p := where .Site.RegularPages ".Date.Year" "ge" 2021 }}
{{ range $p }}
  {{ with $p }}
    {{ partial "archive/archrow.html" (dict "context" . "arch_pages" (first $groupSize $p) "break_at" 2) }}
    {{ $p = after $groupSize $p }}
  {{ end }}
{{ end }}

Is this the “best” method? I have no idea, but it seems pretty clean.

1 Like

Squeaky clean. I’m wondering if it will beat the .Paginate performance in the end.

With 1000 pages and an “archive/archrow.html” partial that simply lists titles, the pagination approach took about 2 seconds. The “squeaky clean” approach took about 0.4 seconds.

1 Like

Yep it shaved off quite a bit of time. Can confirm this is the fastest method “so far”.

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