I have a paginator on the home page for my blog teasers. I also have a paginator for tags. The corresponding blog teasers are also displayed there. For the tag hugo, for example, the second page has the URL https://tekki-tipps.de/en/tags/hugo/page/2. So far so good.
Google finds fault with the correct URL for Paginator pages. By default, Hugo does not display any page information for page 2 and larger for permalinks. So I used Paginator to assemble an appropriate canonical link. This works on the home page, but not for the tags.
In the baseof.html in the <head> I have the following code:
{{ if .IsHome }}
{{ $paginator := .Paginate (where .Site.RegularPages "Section" "blog") }}
{{ if eq $paginator.PageNumber 1 }}
<link rel="canonical" href="{{ .Permalink }}" />
{{ else }}
<link rel="canonical" href="{{ .Permalink }}page/{{ $paginator.PageNumber }}/" />
{{ end }}
{{ else }}
{{ $pag := .Paginate (where .Site.RegularPages "Section" "taxonomy") }}
{{ if eq $pag.PageNumber 1 }}
<link rel="canonical" href="{{ .Permalink }}" />
{{ else if gt $pag.PageNumber 1 }}
<link rel="canonical" href="{{ .Permalink }}page/{{ $pag.PageNumber }}/" />
{{ else }}
<link rel="canonical" href="{{ .Permalink }}" />
{{ end }}
{{ end }}
The error message is:
ERROR 2021/08/22 18:21:09 Failed to render pages: render of "page" failed: "----tekki-tipps/themes/tekki/layouts/_default/baseof.html:57:19": execute of template failed: template: _default/single.html:57:19: executing "_default/single.html" at <$pag.PageNumber>: error calling PageNumber: runtime error: invalid memory address or nil pointer dereference
The working code looks like this and the result can be seen live on the internet:
{{ if .IsHome }}
{{ $paginator := .Paginate (where .Site.RegularPages "Section" "blog") }}
{{ if eq $paginator.PageNumber 1 }}
<link rel="canonical" href="{{ .Permalink }}" />
{{ else }}
<link rel="canonical" href="{{ .Permalink }}page/{{ $paginator.PageNumber }}/" />
{{ end }}
{{ else }}
{{ $pag := .Paginate .Pages }}
<link rel="canonical" href="{{ .Permalink }}" />
{{ end }}
How do I change the canonical link for page 2 and larger in the tags so that it also works there?