Skip to content
This repository was archived by the owner on Dec 30, 2022. It is now read-only.

Commit 09bf657

Browse files
committed
Add optional table of contents for blog posts
1 parent 80181ad commit 09bf657

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

exampleSite/config.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ posts_navigation = true
4242
# issoHost = "comments.domain.tld:1234"
4343
# githubRepo = "githubUsername/repositoryName/tree/master"
4444
small_banner_logo = false
45+
tableofcontents = true
4546

4647
[params.colors]
4748
identifier = "#527fc1f"

layouts/partials/blog_single.html

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@
4545
</div>
4646
</div>
4747
<div class="markdown">
48+
{{ if .Params.toc | default false }}
49+
{{ partial "table_of_contents.html" . }}
50+
{{ end }}
4851
{{ partial "content" . }}
4952
</div>
5053
{{ if .Site.Params.share }}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{{/* https://gist.github.com/skyzyx/a796d66f6a124f057f3374eff0b3f99a */}}
2+
{{/* https://github.com/gohugoio/hugo/issues/1778 */}}
3+
4+
{{/* ignore empty links with + */}}
5+
{{ $headers := findRE "<h[1-4].*?>(.|\n])+?</h[1-4]>" .Content }}
6+
{{ .Scratch.Set "last_level" 1 }}
7+
8+
{{/* at least one header to link to */}}
9+
{{ $has_headers := ge (len $headers) 1 }}
10+
{{ if $has_headers }}
11+
<aside class="table-of-contents">
12+
<ul class="toc-h{{ . }}">
13+
{{ range $headers }}
14+
{{ $header := . }}
15+
{{ $base := ($.Page.File.LogicalName) }}
16+
{{ $anchorId := ($header | plainify | htmlUnescape | anchorize) }}
17+
{{ $href := delimit (slice $base $anchorId) "#" | string }}
18+
<li><a href="{{ relref $.Page $href }}">{{ $header | plainify | htmlUnescape }}</a></li>
19+
{{ end }}
20+
</ul>
21+
</aside>
22+
{{ end }}

0 commit comments

Comments
 (0)