Linkified Section Headings in Hugo-⁠Generated Web Pages

Page contents

1. Why linkify section headings

If a section heading is a link to itself, people can right-click the heading, copy the link to their clipboard, and then share it anywhere they like. For example, the link to this section of this page is:

The yellow highlighted part of this URL (#_why) is called the document fragment reference.

Sections 2 and 3 below describe how to automatically linkify sections headings in articles that are written in AsciiDoc and Goldmark-flavored Markdown, which are two of the markup languages that Hugo supports.

2. AsciiDoc

To linkify the section headings of all Hugo project articles that are written in AsciiDoc, put the following (or a superset of the following) in the project’s config.yaml.

   sectlinks: true


You can see this :sectlinks: AsciiDoc attribute in action in the section headings in this page (which is written in AsciiDoc).

For more about configuring AsciiDoc in a Hugo project, see Infinite Ink’s Intertwingling AsciiDoc and Hugo⁠, especially section 2.


3. Goldmark-flavored Markdown

To linkify the section headings of all Hugo project articles that are written in Goldmark-flavored Markdown, you can use a Hugo Markdown render hook.

Example 1: Infinite Ink

Here is the Markdown render hook that Infinite Ink uses:

Infinite Ink’s layouts/_default/_markup/render-heading.html
<h{{ .Level }} id="{{ .Anchor | safeURL }}">
         <a href="#{{ .Anchor | safeURL }}">{{ .Text | safeHTML }}</a>
</h{{ .Level }}>

You can see this render-heading hook in action in the section headings in Infinite Ink’s Ordinary and Extraordinary Markdown (which is written in Goldmark-flavored Markdown).


Example 2:

The Markdown render hook that the website uses is at:

In January 2021, it looks like this:

<h{{ .Level }} id="{{ .Anchor | safeURL }}">{{ .Text | safeHTML }}
{{- if and (ge .Level 2) (le .Level 4) }}{{" " -}}
<a class="header-link" href="#{{ .Anchor | safeURL }}"><svg class="fill-current o-60 hover-accent-color-light" height="22px" viewBox="0 0 24 24" width="22px" xmlns=""><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></a>
{{- end -}}
</h{{ .Level }}>

The <svg …​ code above displays a link image (🔗) which is linkified by the surrounding code. You can see this render hook in action throughout the Hugo Documentation.



To comment, you must be signed in to GitHub.