Hugo: How to create URL links to in-post headers
Date: 2018-12-06 | hugo | guide | header | links | markdown |
Problem: I am creating a long post summarizing many different sub items as part of my QCon SF 2018 debrief and want to create a table of contents of sorts in order to help readers jump to the locations they desire. To do this, I was thinking of linking directly to the headings of each of the individual talks similar to how Wikipedia allows you to share a specific heading themselves. How can I go about doing this?
Solution: To create a link to a specific header, you basically just need to create a link the same way you would create any other, but instead of supplying a url, just supply the relative url of that specific header. This is a little confusing, but bare with me for a sec.
Under the hood, Hugo is just going to be creating a link to a page element's ID field, for example:
<div id="my-div" />
So in a url, you would link to this div via MYURL/my/path#my-div. To support this, Hugo creates a unique id field on each header which consists of the header's text in all lowercase with all punctuation replaced with -
.
To double-check what id you need to be linking to, you can:
- fire up a local instance of your site with
hugo serve
- add a header to your new post/page
- inspect that element in your web browser
- find the
id
field on your element
Equipped with this knowledge, you can create an id-link to your header in the following ways:
- Full url path with id -> MYWHOLEURL/path/to/post#my-div-id
- Relative url path with id (assuming you have relative urls turned on) -> /path/to/post#my-div-id
- Just id (assuming you have relative urls turned on) -> #my-div-id
So, for instance, in my QCon SF 2018 debrief, I have a link to the Key takeaways section declared with:
[Key takeaways](#key-takeaways)
which Hugo will transform into its fully-qualified form as part of the generation process.
Want more like this?
The best / easiest way to support my work is by subscribing for future updates and sharing with your network.