โ ๏ธ Warning: This post is over a year old, the information may be out of date.
๐ Hugo Toc (Table of Content) with spoiler
๐ | โฐ 2 minutes
I wonder how to create ToC (Table of Content) using Hugo and it seem much easier compare to Jekyll, because it have built in function {{ .Page.TableOfContents }}
that ready to use . But I still need hacking the some files, to make it prettier. I will document it and share here.
ToC
Set suitable variable on config.yml
Open config.yml
and put snippet provided below on your file. You know how to find it right?
You may change values of startLevel
and endLevel
to whatever number that suite your need. Same goes for ordered
value, you can set as true
to get ordered list.
[markup]
[markup.tableOfContents]
startLevel = 2
endLevel = 5
ordered = false
Add new shortcode
template
Now add new files called as toc.hml
inside layouts/shortcodes/
directory and insert snippet provided.
<!-- ToC - Author: Robbi Nespu -->
{{- $id := printf "spoiler-%d" .Ordinal -}}
<details class="spoiler {{ .Get "class" }}" {{ with .Get "style" }}style="{{ . | safeCSS }}"{{ end }} id="{{$id}}">
<summary>Click to view ToC</summary>
<aside class="toc">
<a class="toc-header">Table of content</a>
{{ .Page.TableOfContents }}
</aside>
</details>
Some touch-up and make-up
To make it look nice, we decorate it with CSS, Ehemm-ehem mine implementation maybe look ugly for you, so modified it as you need, I not a front-end developer, that why my CSS skill are limited. Yeah, I am suck!
/* ToC - Author: Robbi Nespu */
.toc {
border: .15rem solid #757575;
padding: 1rem;
margin-top: 1rem;
margin-bottom: 1em;
color: #757575;
}
.toc-header {
color: #757575;
font-size: 1.5rem;
}
#TableOfContents > ul {
list-style-type: none;
padding-left: 1em;
}
#TableOfContents > ul > li ul {
list-style-type: none;
padding-left: 1em;
}
Append this CSS code to your own theme main CSS. You theme maybe support to load custom CSS. Whatever strategy you use, it doesn’t matter as long it loaded on stylesheet.
Read to use
Then simply just use shortcode
{{< toc >}}
inside markdown and it will generated ToC for you.
---
title: "Hugo Toc (Table of Content) with spoiler"
date: 2021-06-24T13:08:26+08:00
---
{{< toc >}}
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat.
Posted by: Hugo