Last active
February 27, 2023 04:21
-
-
Save skyzyx/a796d66f6a124f057f3374eff0b3f99a to your computer and use it in GitHub Desktop.
Hugo Partial for Generating the Table of Contents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
{{- partial "toc.html" . -}} | |
... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{/* https://github.com/gohugoio/hugo/issues/1778 */}} | |
{{/* ignore empty links with + */}} | |
{{- $headers := findRE "<h[2-4].*?>(.|\n])+?</h[2-4]>" .Content -}} | |
{{ .Scratch.Set "last_level" 1 }} | |
{{/* at least one header to link to */}} | |
{{- $has_headers := ge (len $headers) 1 -}} | |
{{- if $has_headers -}} | |
<aside class="table-of-contents"> | |
<details> | |
<summary> | |
<b>Table of Contents</b> | |
</summary> | |
{{- range $headers -}} | |
{{- $header := . -}} | |
{{- $base := ($.Page.File.LogicalName) -}} | |
{{- $anchorId := ($header | plainify | htmlUnescape | anchorize) -}} | |
{{- $href := delimit (slice $base $anchorId) "#" | string -}} | |
{{- range findRE "[2-4]" . 1 -}} | |
{{- $next_heading := (int .) -}} | |
{{- if gt $next_heading ($.Scratch.Get "last_level") -}} | |
<ul class="toc-h{{ . }}"> | |
{{- else if lt $next_heading ($.Scratch.Get "last_level") -}} | |
</ul> | |
{{- end -}} | |
<li><a href="{{ relref $.Page $href }}">{{- $header | plainify | htmlUnescape -}}</a></li> | |
{{ $.Scratch.Set "last_level" $next_heading }} | |
{{- end -}} | |
{{- end -}} | |
</details> | |
</aside> | |
{{- end -}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But @Iooeee 's code rendered too many end tags 😂
I have investigated into it and wrote a blog post
If the blog is too abstract, here is the code