.Fragments not working with .GetPage

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.

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

No, it should work for any page backed by markdown, but there’s a potential chicken and egg situation here when you in a shortcode try to bite your tail … Your post is a little litght on the details, but the trick to make the Fragments visible for yourself would be to use the {{< delimiter when you include the shortcode. Note that referencing other pages should always work.

Thanks for confirming.

Yes, I’m using {{< (perhaps my code block was scrolled past those first two lines?).

Confirmed that it works as expected in a test project.

Tracked down my issue to the fact that I was unknowingly referencing a page bundle. My bad.

Also discovered that trying to reference HeadingsMap with a heading that doesn’t exist will crash Hugo. A safe way to reference the title of a fragment heading is:

    {{- if $pg.Fragments.Identifiers.Contains $anchor -}}
    {{- with index $pg.Fragments.HeadingsMap $anchor -}}
      {{- $title = .Title -}}
    {{- end -}}
    {{- end -}}

Many thanks. Fragments is a very cool feature :+1:

1 Like

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