TableOfContents doesn't render headings correctly that contains shortcode

Hi, I found that TableOfContents would not render the shortcode that with the headings.

## Heading with Shortcode: {{< foo >}}

The shortcode output the bar only for testing.

As the image shown, the heading was rendered as Heading with Shortcode: HAHAHUGOSHORTCODE4251s1HBHB.

Would this be considered as a feature? If so, I will create a feature request on GitHub then.

Use the {{% foo %}} notation instead.

3 Likes

Thanks!

@jmooring In my case, the {{% %}} syntax prevents the HAHAHUGOSHORTCODE issue but doesn’t render icons in TOC.

Test markdown:

Reddit icon: {{< icon "reddit" >}}

## Use `{{</* */>}}` syntax {{< icon "reddit" >}}

## Use `{{%/* */%}}` syntax {{% icon "reddit" %}}

Result:

Both unsafe = true and unsafe = false in goldmark.renderer don’t help.

Details:

Hugo v0.147.7

Icon shortcode: blowfish/layouts/shortcodes/icon.html at main · nunocoracao/blowfish · GitHub

{{ $icon := resources.Get (printf "icons/%s.svg" ($.Get 0)) }}
{{ if $icon }}
  <span class="relative inline-block align-text-bottom icon">
    {{ $icon.Content | safeHTML }}
  </span>
{{ end }}

Is there a way to make TOC render HTML content from shortcodes properly?

It already does. The problem is that both your shortcode and the icon file contain newlines, and per the CommonMark spec the heading element ends at the first newline. Try it yourself:

https://spec.commonmark.org/dingus/?text=%23%23%20Heading%20<span> something <%2Fspan>

To do…

Step 1: Override the icon shortcode

{{- with resources.Get (printf "icons/%s.svg" ($.Get 0)) -}}
  <span class="relative inline-block align-text-bottom icon">
    {{- strings.Replace .Content "\n" "" | safeHTML -}}
  </span>
{{- end -}}

In the above we remove newlines from the SVG file with strings.Replace, and we remove whitespace from the shortcode itself using the {{- and -}} action delimiters.

Step 2: Configure goldmark to treat HTML in Markdown as safe

In your site config:

[markup.goldmark.renderer]
unsafe = true

The configuration above is safe if you control the content.

Example

git clone --single-branch -b hugo-forum-topic-55399 https://github.com/jmooring/hugo-testing hugo-forum-topic-55399
cd hugo-forum-topic-55399
hugo server
3 Likes

Wow, thank you very much for your clear explanation. I was genuinely surprised to learn that the problem was just caused by a missing line break, and I didn’t expect it would turn into you helping me debug my setup. Truly appreciate your help and generosity.

2 Likes

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