Applying headings in shortcodes to the table of contents

I’m currently working on a project that requires a lot of re-using information on multiple pages via shortcodes. In some cases, that means pulling in structured data using site.Data and in other cases that means pulling in small bits of Markdown using readFile. The problem I’m running into is that the TableOfContents doesn’t seem “aware” of anything that’s introduced into the page via shortcodes, which means that none of the headers inside shortcodes end up in the table of contents. I’m really hoping to avoid the only workaround I can think of, which is using Scratch or some other mechanism to build the TOC by hand.

Is there a way around this? Perhaps a configuration parameter I’m not seeing in the docs?

Call the shortcode like this {{% foo %}} instead of this {{< foo >}}.

See https://gohugo.io/content-management/shortcodes/#shortcodes-with-markdown.

Shortcodes using the % as the outer-most delimiter will now be fully rendered when sent to the content renderer. They can be part of the generated table of contents, footnotes, etc.

If your shortcode includes HTML, you will have to change your configuration setttings:

[markup.goldmark.renderer]
unsafe = true

Otherwise the HTML will be rendered as <!-- raw HTML omitted -->.