zwbetz
April 7, 2019, 3:56pm
1
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.
ju52
April 8, 2019, 3:30pm
2
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.
zwbetz
April 8, 2019, 3:39pm
3
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.
zwbetz
April 8, 2019, 4:20pm
5
Nice. Going to play around with this tonight and report back.
zwbetz
April 10, 2019, 2:47pm
6
@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: https://zwbetz.com/create-header-links-hugo-vs-javascript/
1 Like
ju52
April 12, 2019, 8:08am
7
svg icons can used directly from fonts like
zwbetz
April 12, 2019, 11:08am
8
Indeed. I imported the feather script because I may use other icons in the future and it’s only a few kb