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>
</h2>
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>
</h2>
kindly tell me the error from the function that I made
In the event you want to do this on the client:
/**
* Anchor for ID BPNY
**/
var anchorForId = function (id) {
var anchor = document.createElement("a");
anchor.className = "header-link";
anchor.href = "#" + id;
anchor.innerHTML = ' <svg class="fill-current o-60 hover-accent-color-light" height="22px" viewBox="0 0 24 24" width="22px" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1zM8 13h8v-2H8v2zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5z"/></svg>';
return anchor;
};
var linkifyAnchors = function (level, containingElement) {
var headers = containingElement.getElementsByTagName("h" + level);
for (var h = 0; h < headers.length; h++) {
var header = headers[h];
if (typeof header.id !== "undefined" && header.id !== "") {
header.appendChild(anchorForId(header.id));
}
}
This file has been truncated. show original
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"> 🔗︎</a> ${3}` | safeHTML }}
</div>
{{- 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.
4 Likes
@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
@TotallyInformation
me too 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
LMK when you get this figured out. Thanks!