Adding anchor next to headers

Your code

{{ .Content | replaceRE "(<h[1-6] id=\"(.+)\".*>)(.*)(</h([1-6])>)" "<a class=\"h${5}-anchor\" href=\"#${2}\">#</a>${1}${3}${4}" | safeHTML }}

(…I just escaped the " of the class…)

worked like charm. Thank you!

The only thing I had to modify was to set my headings to inline (if not the a-tag and the h-tag will appear on two different lines) and to adapt the font size of the a-tag to that of the h-tag).

It works and looks really good.

BTW: I saw it first on this page.

Summary

I have a partial with the name headings-anchor.html which I call in my list.html with {{ partial "headings-anchor.html" .Content }}. Then I choose one of the following options:

Anchor after heading

{{ . | replaceRE "(<h[2-6] id=\"([^\"]+)\".+)(</h[2-6]+>)" "${1}&nbsp;<a class=\"anchor\" href=\"#${2}\">#</a> ${3}" | safeHTML }}

Output

My heading 1 # 

My heading 2 #

Anchor before heading (without CSS counters)

{{ . | replaceRE "(<h[2-6] id=\"(.+)\".*>)(.*)(</h[2-6]>)" "${1}<a href=\"#${2}\">#</a>${3}${4}" | safeHTML }}

Output

# My heading 1

# My heading 2

Anchor before heading (with CSS counters)

{{ . | replaceRE "(<h[2-6] id=\"(.+)\".*>)(.*)(</h([2-6])>)" "<a class=\"h${5}-anchor\" href=\"#${2}\">#</a>${1}${3}${4}" | safeHTML }}

Output

# 1. My heading 1

# 2. My heading 2

For the last option I use the following CSS:

CSS counters


h1 {
  counter-reset: h2;
}

h2::before {
	counter-increment: h2;
	content: counter(h2) ". ";
}

h2 {
  counter-reset: h3;
}

h3::before {
	counter-increment: h3;
	content: counter(h2) "." counter(h3) ". ";
}

h3 {
  counter-reset: h4;
}

…and so on.

h-anchor and h on same line

h2,
h3,
h4,
h5,
h6 {
    display: inline;
}

Set space between # and heading

.h2-anchor,
.h3-anchor,
.h4-anchor,
.h5-anchor,
.h6-anchor {
    margin-right: 1em;
}

and the font sizes of h-anchor and h should correspond.

Maybe it’s worth mentioning that replaceRE over the .Content here isn’t necessary anymore, since this issue could now be solved by using markdown render hooks.

2 Likes

My initial requirement was to put # before h1 headings, ## before h2 heading, etc.

As others have mentioned, this can be achieved with render hooks. This is what I’m doing:

Put this in your theme’s layouts/_default/_markup/render-heading.html file:

<h{{ .Level }} id="{{ .Anchor | safeURL }}">
    <a class="heading-anchor" href="#{{ .Anchor | safeURL }}">
        {{ strings.Repeat .Level "#" }}
    </a>
    {{ .Text | safeHTML }}
</h{{ .Level }}>
6 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.