I would like to update the render hook documentation for headings, and would like examples of valid use cases. If you use heading render hooks, why? Please provide an example. Thanks!
Two I can think of are to make headings linkable and to keep the headings correct when a post isn’t on it’s own and is part of list.
For a linkable heading:
<h{{ .Level }}{{ range $k, $v := .Attributes }}
{{ $k }}= {{ $v }}
{{ end }}>
<a href="#{{ .Anchor }}">
{{ .Text }}
</a>
</h{{ .Level }}>
To keep headings in order:
{{ $demotion := .Scratch.Get "demotion" | default 0 }}
{{ $level := add $demotion (int .Level) }}
<h{{ $level }}>{{ .Text }}</h{{ $level }}>
In a list section, before you render .Content
, do something like {{ .Scratch.Set "demotion" 1 }}
.
Thanks! This is great.
But I don’t understand why you are adding an anchor. If an element in the DOM has an id of “foo”, then this anchor <a href="#foo">foo</a>
will jump to it. So we can just add an id to the heading instead, which is what Hugo does by default without a heading render hook. Or am I missing something?
It puts the attributes in the heading element via . Attributes
. I did this since it makes it easier to discover the link. I guess you could have the anchor next to the heading text.