No TableOfContents when reusing content

I’ve got a shortcode which inserts snippets of Markdown in a topic:

{{ $src := "" }}
{{- if .IsNamedParams -}}
    {{- $src = .Get "src" -}}
{{- else -}}
    {{- $src = .Get 0 -}}
{{- end -}}
{{- with .Site.GetPage $src -}}
    {{- .Content | markdownify -}}
{{- else -}}
    {{- errorf "Can't find snippet reference %q in topic %s." (.Get 0) .Position -}}
{{- end -}}

This allows me to reuse text throughout my site - I use {{< snippet src="snippets/mytopic/index.md" >}} and the text appears as predicted.

But there’s no TableOfContents on the right - I assume because Hugo thinks there’s no content (just a shortcode) so the .TableOfContents variable is empty.

Is there anything I can do to fix this?

1 Like

First, call your shortcode with the {{% foo %}} notation. This will force the shortcode contents to be rendered before we send the content to the markdown renderer (Goldmark).

{{% snippet src="/snippets/mytopic/index.md" %}}

Second, change your shortcode to get the .RawContent (the markdowwn) of the snippet page.

{{ $src := "" }}
{{- if .IsNamedParams -}}
    {{- $src = .Get "src" -}}
{{- else -}}
    {{- $src = .Get 0 -}}
{{- end -}}
{{- with .Site.GetPage $src -}}
    {{- .RawContent -}}
{{- else -}}
    {{- errorf "Can't find snippet reference %q in topic %s." (.Get 0) .Position -}}
{{- end -}}
1 Like

Yet again @jmooring rides to the rescue. Works perfectly. Thank you.

1 Like

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