📢 Actions Speak Louder Than Words!

Hugo Toc (Table of Content) with spoiler

Posted: Jun 24, 2021 | Reading time: 2 min

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.

Click to view 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.

    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 }}

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. 


Discussion and feedback

You can use utterances provided below to post comment on behalf using Github account. Alternatively, you can just send a public comment to my mailing list or send a private message to my e-mail. In a few cases and on certain time, I just don’t have time to moderate them. Please read terms-of-service (ToS) for details.