I’m trying to use page fragments to get the title of a heading for a given page. I’m using .GetPage
to get the page (this works obviously), but the .Fragments
object doesn’t appear to contain any data.
The basic usage looks like this. You can see that I’m testing many conditions on .Fragments
, but none of them are true.
(markdown)
A reflink anchor link: {{< reflink "my-page#my-heading" >}}.
(reflink shortcode)
{{- with .Get 0 -}}
{{- $parts := split . "#" -}}
{{- $pg := $.Site.GetPage (index $parts 0) -}}
{{- $title := $pg.Title -}}
{{- $link := $pg.RelPermalink -}}
{{- $frag := "" -}}
{{- with (index $parts 1) -}}
{{- $frag = . -}}
{{- if $pg.Fragments.Identifiers.Contains . -}}
{{- $frag = "found" -}}
{{- end -}}
{{- if gt ($pg.Fragments.Identifiers.Count .) 0 -}}
{{- $frag = "gt0" -}}
{{- end -}}
{{- if gt (len $pg.Fragments.Identifiers) 0 -}}
{{- $frag = "len gt0" -}}
{{- end -}}
{{- end -}}
<a href="{{ $link }}#{{ $frag }}">{{ $title }} (#{{ $frag }})</a>
{{- end -}}
Am I using fragments correctly?
The Hugo doc for fragments says “returns a list of fragments for the current page” (emphasis my own). Does that mean it won’t work with GetPage
?
I’ve also read the Go doc for fragments and can’t figure out why it’s not working.
I can create a test repo if needed. Thanks!
Hugo env
hugo v0.111.1-39a4a3cf676533859217805c36181c7a3dfa321c+extended darwin/arm64 BuildDate=2023-03-02T10:08:26Z VendorInfo=gohugoio
GOOS="darwin"
GOARCH="arm64"
GOVERSION="go1.20.1"
github.com/sass/libsass="3.6.5"
github.com/webmproject/libwebp="v1.2.4"