Put a header link before all h2 elements

I want to add a header link before all h2 elements in my blog post pages.

I’m currently doing this with JS here, and you can see a demo of what I’m talking about here.

But I’d like to do this with Hugo if possible and reasonable.

A brief summary of how I’m doing it in JS:

  • Create an anchor element that will contain the header link svg (which is replaced later by Feather)
  • Get all h2 headings on the page
  • For each h2, give the anchor href the id of the header, then add the anchor before the header text

Any ideas/examples of how to do this in Hugo are appreciated.

Sorry, have no time to try this

Try to use a shortcode to generate the H2 headers with ancors. With .Scratch.Add the links could be collected and displayed as list.

I want to stay away from using a shortcode since this would require much more effort when writing posts. My current solution is good in this regard as it adds the head links automatically, and I can focus on writing content.

A Hugo templating solution for this will likely require the findRE and replaceRE functions, I just haven’t quite cracked the egg yet.

Yep, that’s the way to go: Adding anchor next to headers

1 Like

Nice. Going to play around with this tonight and report back.

@kaushalmodi Thanks for the help! Took me a bit to wrap my head around the regex and capturing groups. It’s powerful once I understood it. Here is my adapted solution.

Call the partial in my layouts/post/single.html template like

{{ partial "header-link.html" .Content }}

The partial is defined as

{{ . | replaceRE "(<h[2] id=\"([^\"]+)\">)(.+)(</h[2]+>)" `${1}<a class="header-icon-link" href="#${2}"><i data-feather="link"></i></a> ${3}${4}` | safeHTML }}

Which will take take html like this

<h2 id="text">Text</h2>

And convert it to this

<h2 id="text"><a class="header-icon-link" href="#text"><i data-feather="link"></i></a> Text</h2>

Then feather js will convert <i data-feather="link"></i> to an svg icon

The git diff, if you would rather that.

That regex still feels magical to read to me, so wrote a short article that will hopefully lessen the learning curve for others:

1 Like

svg icons can used directly from fonts like

Indeed. I imported the feather script because I may use other icons in the future and it’s only a few kb