Hugo: Adding a Table of Contents

Today I will disuss how to include a Table of Contents (TOC) on a Hugo page. I’ll be referencing the Hugo documentation.

While working through these steps I also found this discussion page had some helpful information.

As usual, I’m working with the Blackburn theme.

Include TOC on every page

The default site hierarchy in the Blackburn theme centres around the \content\post directory. Buried in the \themes directory is a template that defines how a single piece of content from this location is rendered:

  • \themes\blackburn-master\layouts\post\single.html

This is where we need to include our table of contents.

  1. Edit the file single.html and locate the line:

    {{ partial "post_meta.html" . }}
    
  2. Below it add a new line and type:

    {{ .TableOfContents }}
    
  3. Refresh your website and review.

All pages should now automatically include a table of contents based on the headings defined using Markdown (lines starting with #’s).

Include the TOC conditionally

Now, not all my pages need a TOC. Wouldn’t it be great if it was only included on the pages we wanted it? The credit for this solution goes to https://discuss.gohugo.io/t/tableofcontents/1616.

  1. Edit the file single.html again, and replace the earlier entry with:

    {{ if .Params.toc }}
    {{ .TableOfContents }}
    {{ end }}
    
  2. Now on the pages we want a TOC, add the following to the front matter:

    +++
    ...
    toc = true
    ...
    +++
    

Ta-da! Optional TOC for your Hugo pages.