Floating Table of Contents for Hugo Academic Theme

Hugo - Academic Theme

I use the Academic theme for Hugo.

When I originally set up this site, I must have spent several late nights trying to get the floating table of contents to work on the sidebar. The floating table of contents is really cool, it’s part-novelty, but also very functional - it lets you jump between sections of the document and highlights your current section.

However, it doesn’t appear to be built to easily activate a floading table of contents (or at least it’s not documented), so I was trying hard to improvise from various guides online about Hugo (none specific to the Academic theme) until I found this response from CharlieLeee, providing the code to get it to work.

Adding smooth scrolling is a simple addition you can also make while you’re thinking about the Table of Contents anyway (e.g. clicking on the table of contents causes the page to scroll in a smooth manner, as opposed to jumpping as though you clicked a link).

Solution

  1. In the folder /layouts/_default/ you will need to create single.html if it does not exist already. Paste the following code. (Again, credit to CharlieLeee)
{{- define "main" -}}
{{ if .Params.toc }}
<div class="container-fluid docs">
    <div class="row flex-xl-nowrap">
      <div class="d-none d-xl-block col-xl-2 docs-toc">
        <ul class="nav toc-top">
          <li><a href="#" id="back_to_top" class="docs-toc-title">{{ i18n "on_this_page" }}</a></li>
        </ul>
        {{ .TableOfContents }}
        {{ partial "docs_toc_foot" . }}
      </div>
      <main class="col-12 col-md-0 col-xl-10 py-md-3 pl-md-5 docs-content" role="main">
{{ end }}
        <article class="article">
            {{ partial "page_header" . }}
            <div class="article-container">
              <div class="article-style">
                {{ .Content }}
              </div>
              {{ partial "page_footer" . }}
            </div>
        </article>
  {{ if .Params.toc }}
      </main>
    </div>
  </div>
  {{ end }}
{{- end -}}
  1. In every post you make where you would like a Table of Contents, you will need to ensure that you add toc: true in your front matter. Don’t forget that if you ever want an additional Table of Contents in the body of your text, you can always add <h2>Table of Contents</h2>

  2. To add smooth scrolling, go to /assets/scss/ where you will need to create custom.scss if it does not exist already (the /scss/ folder may also not exist by default, but I no longer recall). Paste the following code:

html {
	scroll-behavior: smooth;
}
Eric Fong, CPA, CA, CPA (Illinois)
Eric Fong, CPA, CA, CPA (Illinois)
Senior Tax Manager

I solve complex problems.

Related