Add Anchor Links to Hugo Headings
Hugo already gives rendered headings an id. With one template change, the heading text itself can link to that ID, making it easy to copy a URL for a particular section.
Replace {{ .Content }} in the default single-page layout with this expression:
{{ .Content | replaceRE "(<h[1-6]\\sid=\"([^\"]+)\"\\s?>)(.+)(</h[1-6]+>)" "${1}<a href=\"#${2}\">${3}</a>${4}" | safeHTML }}
The regular expression captures the opening heading tag, its id, the heading text, and the closing tag. replaceRE then wraps the text in an anchor pointing back to that ID.
safeHTML is needed because the replacement creates HTML rather than plain text. That also means I would use this only with content I trust. Regular expressions and generated HTML are a compact solution here, but they are not a general-purpose HTML parser.
Enjoyed reading this?
If you found this article helpful, consider supporting my writing. Every little bit helps keep this blog going.
Related articles
- Customizing Hugo’s RSS Feed
Adjust Hugo RSS titles, descriptions, content, and section filtering while keeping the generated feed valid and easy to discover.
- Organizing Hugo Content With Tags and Categories
Organize Hugo content with a small, deliberate set of tags, categories, or custom taxonomies that lead to useful archive pages.
- A More Useful 404 Page in Hugo
Turn Hugo's 404 page into a useful route back to the homepage, search, or content visitors may have wanted.