Hi @kc0bfv, thank you for the suggestion. I’ve explored using custom shortcodes but these approaches break the Table of Contents.
I have a sample markdown file containing one h1
and two h2
headers with some content:
# Title
Lorem ipsum dolor sit amet.
{{< hanchor "## Anchor Title" >}}
Consectetur adipiscing elit.
## Non Anchor Title
Suspendisse potenti.
My custom shortcode layouts/shortcodes/hanchor.html
:
{{ with .Get 0 }}
{{ $data := split . " " }}
<!-- Get the heading level, heading text, and anchorized id -->
{{ $htype := chomp (delimit (first 1 $data) " ") }}
{{ $hval := delimit (after 1 $data) " " }}
{{ $hid := anchorize $hval }}
<!-- Attempt 1: Construct new markdown, making the heading a link -->
<!-- {{ print $htype " [" $hval "](#" $hid ")" | $.Page.RenderString }} -->
<!-- {{ print $htype " [" $hval "](#" $hid ")" | markdownify }} -->
<!-- This fails as anchorized id mismatches constructed a tag -->
<!-- Attempt 2: Manual anchor id on heading and link -->
{{ $hlen := len $htype }}
{{ $stag := print "<h" $hlen " id=\"" $hid "\">" }}
{{ $etag := print "</h" $hlen ">" }}
{{ $link := print "[" $hval "](#" $hid ")" | markdownify }}
{{ print $stag $link $etag | safeHTML}}
{{ end }}
The outputted {{ .Content }}
looks okay:
<h1 id="title">Title</h1>
<p>Lorem ipsum dolor sit amet.</p>
<h2 id="anchor-title"><a href="#anchor-title">Anchor Title</a></h2>
<p>Consectetur adipiscing elit.</p>
<h2 id="non-anchor-title">Non Anchor Title</h2>
<p>Suspendisse potenti.</p>
Unfortunately my Table of Contents is no longer accurate as it is missing the anchor-title
:
<nav id="TableOfContents">
<ul>
<li><a href="#title">Title</a>
<ul>
<li><a href="#non-anchor-title">Non Anchor Title</a></li>
</ul>
</li>
</ul>
</nav>
Curious to hear if you have additional advice or next steps. Thanks!