HUGO

Reuse content and TOC

Hi,
I want to use content in several places on the site, like snippets. I need snippets to be included in the TOC.

I have tried using Headless Bundle (Page Bundles | Hugo) but unfortunately nothing is showing in the TOC. I would like to avoid rewriting the TOC. What am I missing here?

Please provide an example of a “snippet.”

Snippet’s code:

{{ $filename := .Get 0 }} 
{{ with .Site.GetPage "/snippets" }}
{{ $filename := (print $filename ".md") }}
    {{ with .Resources.GetMatch $filename }} {{ .Content | markdownify }} {{ end }}
{{ end }}

I’ve tried snippet from docs but same results.

Please provide an example of a “snippet.” You provided a shortcode template. I want to know what the content looks like.

So snippet is located in /content/snippets and there I have:

index.md

---
headless: true
---

And snippet that I want to use:

---
title: "Test data"
---

### This is a header that should be in TOC
And some description that I want to use in many places

The shortcode is called with {{% snippet "test-snippet" %}}

This approach will insert the snippet with one heading that will be picked up by the .TableOfContents.

Site configuration

[markup.goldmark.renderer]
  unsafe = true

[[cascade]]
  [cascade._build]
    render = "never"
    list = "never"
  [cascade._target]
    path = "/snippets/**"

Structure

content/snippets/
├── _index.md
├── snippet-1.md
└── snippet-2.md

content/snippets/_index.md

+++
title = "Snippets"
date = 2021-07-29T06:36:59-07:00
draft = false
+++

content/snippets/snippet-1.md

+++
title = "Snippet 1"
date = 2021-07-29T04:53:34-07:00
draft = false
heading = "This is the Snippet 1 Heading"
+++
This is the **snippet** 1 body.

layouts/shortcodes/snippet.html

{{ $path := "" }}
{{ $level := 2 }} {{/* Default */}}

{{ if .IsNamedParams }}
  {{ $path = print "snippets/" (.Get "file") }}
  {{ $level = .Get "level" }}
{{ else }}
  {{ $path = print "snippets/" (.Get 0) }}
  {{ $level = .Get 1 }}
{{ end }}

{{ with site.GetPage $path }}
  {{ strings.Repeat $level "#" }} {{ .Params.heading }}
  {{ .Content }}
{{ else }}
  {{ errorf "The %s shortcode could not find %s. See %s" .Name $path .Position }}
{{ end }}

Usage

{{% snippet file="snippet-1" level=2 %}}
{{% snippet snippet-1 2 %}}

Try it:

git clone --single-branch -b hugo-forum-topic-34027 https://github.com/jmooring/hugo-testing hugo-forum-topic-34027
cd hugo-forum-topic-34027
hugo server
1 Like

Works great, thanks @jmooring!

I just found one problem that I have not figured out how to solve. The index page for snippets is still published, despite the site configuration setting. Working on it…

To prevent creation of the snippets list page, you must create snippets/_index.md. I have edited the post marked as a solution and updated the test repository.

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