Hugo Guide: Add Table of Contents In Markdown

Author Icon Post Nurahmat

Calendar Icon Post

#hugo

Post's reading time 2 min read

Hugo is my final choice after get confused to choose what static site generator should I use. I ended up with this amazing SSG!

And I’m quite happy because this is the best website that I ever had in my live it’s has rich feature of the way formatting the text.

TOC Anywhere Now, I’m Happy

a thing that has huge impact for the reason why I stick with Hugo is actually I can add table of contents in the middle my article as shown below.

Note ! I only give you the basic implementation neither the style or javascript code, I believe you can do it by yourself.

You see it? Well, how amazing is it! In this article I’m gonna share with you how I do it, keep reading!

Make TOC in Your Markdown

According to the hugo documentation, we can add table of contents with this simple code.

hugo
{{ .TableOfContents }}

Unexpectedly, I feel like an Idea come out from my brain.

How if I add this at the middle on my article, maybe I have to make custom shortcodes.

My first try I get an error, because there’s something wrong with my custom shortcodes, and then I review again the hugo documentation about shortcodes. Got it!

Creating Custom Shortcodes

Assume that you already know where the custom shortcodes located layouts/shortcodes/ yep, in this directory.

Let’s create file named toc.html and add inside that this code.

toc.html
{{ .Page.TableOfContents }}

You got it? Something changed, I added .Page it refers to the content file as hugo docs said.

Then, just save the file and follow the usage guide.

Usage

We already have custom shortcodes that show table of contents. Now, you may know or not how to use it, I’ll still give you the tutorial.

Simply, just put the shortcodes {{< toc >}} inside your markdown file as shown below.

---
title: TOC Usage Guide For Hugo
draft: true
---

## Some title goes here
{{< toc >}}
### Subtitle
Some Paragraph

Conclusion

Shortcodes is quite awesome for more flexibility and customization of your content generated by Hugo.

Was this helpful? Anyway, sorry about my English.