Best Practice Adding Link to Heading

Hi all,

I need to add a link to every heading inside the content, for example

<!-- Before -->
<h2 id="foo">Foo</h2>

<!-- After -->
<h2 id="foo">
 <a title="foo" href="#foo">Foo</a>

I try using replaceRE function in my partial template

{{ .Content | replaceRE "(<h[2-9] id=\"([^\"]+)\".+)(</h[2-9]+>)" "${3}<a title=\"${2}\">${1}</a>${3}" | safeHTML }}

almost succeeded as expected, but I found the oddity by the appearance of an empty link element above the headline

here’s the output

<a title="foo"></a> 
<h2 id="foo">
 <a title="foo" href="#foo">Foo</a>

kindly tell me the error from the function that I made

In the event you want to do this on the client:

1 Like

This is what I have in my single.html:

    {{- with .Content -}}
    <div itemid="articleBody">
      {{ . | replaceRE "(<h[1-9] id=\"([^\"]+)\".+)(</h[1-9]+>)" `${1}<a href="#${2}" class="hanchor" ariaLabel="Anchor"> 🔗&#xFE0E;</a> ${3}` | safeHTML }}
    {{- end -}}

That adds an anchor to every heading. It is hidden by default, I use the following CSS to make it visible when you mouse over the heading (I only use heading 1-4):

.hanchor { font-size: 100%; visibility: hidden; color:silver;}
h1:hover a, h2:hover a, h3:hover a, h4:hover a { visibility: visible}

I think someone in this forum put me onto that, I originally used JavaScript but this is much better.


@rdwatters javascript is awesome, but this time I would like to use Hugo function. I will save your suggestion if it cannot eventually use the hugo function


me too :slightly_smiling_face: but I found no solution if the goal is to change regular heading into heading with link

thank you guys

I’m slightly confused. The code I gave is easily adapted to output the heading as a link. I just choose to add a link at the end instead.

I figured as much, but also figured there wasn’t much harm in throwing out the way the Hugo docs is getting it done :slight_smile:

LMK when you get this figured out. Thanks!