Creating table of contents in Hugo

Aug 02, 2021 by Kolappan N

Adding table of contents to a Hugo page is a easy as Hugo automatically parses a markdown file and generates a index and stores it in a TableOfContents variable for each page.

You can call it by using, {{ .Page.TableOfContents }} which will be replaced by a nav section similar to the following,

<nav id="TableOfContents">
    <ul>
        ...
    </ul>
</nav>

If you have a CSS style set for nav kindly check it. I had my navbar styles applied to the Table of Contents.

By default the index will contain h2 and h3 headings only(represented in markdown by ## and ###). You can change in config.

markup:
  tableOfContents:
      startLevel: 2 # If start level is two it ignores h1. Useful if you have page title as h1 and don't want it in the Index
      endLevel: 3 # The last level of heading to include. Maximum is 6 which coressponds to h6
      ordered: false # whether the table of contents should be bullets or numbered

Simply put you can add {{ .Page.TableOfContents }} anywhere in the page where you want to add a table of contents. I also created a shortcode to ease things a bit. The shortcode I use is as follows,

<div>
    <hr>
    <h2>Table Of Contents</h2>
    {{ .Page.TableOfContents }}
</div>
Tags: Hugo