Add table of contents to hugo site using blogdown

I am using a Rmd file with blogdown to generate a static website. On a particular page I am writing, I would like to add a table of contents toc.

First I tried amending my header yaml like so:

output: 
  html_document:
    toc: true 

But after building, no toc were displayed.

I then tried typing just {{.TableOfContents}} into the whitespace of my Rmd file. WHen building and serving, this just rendered {{.TableOfContents}} as text.

I then tried adding it into an html block like so:

{{.TableOfContents}}

This just pasted '{{.TableOfContents}}' in a code highlighted line:

I asked GPT which told me to create a file in layouts/shortcodes and call it toc.html with the content of the shortcode {{.TableOfContents}}, then to refer to {{% toc %}} inside my html block.

This results in the following error when attempting to build:

Total in 47 ms
Error: error building site: failed to render shortcode: "/home/some/path.md:14:1": failed to render shortcode "toc": failed to process shortcode: "/some/path/shortcodes/toc.html:1:3": execute of template failed: template: shortcodes/toc.html:1:3: executing "shortcodes/toc.html" at <.TableOfContents>: can't evaluate field TableOfContents in type *hugolib.ShortcodeWithPage

How can I get a toc to appear in my rendered html page?

This could depends of the theme you are using with blogdown. Usually the TOC feature will be associated with the theme you are using, which will have in its layout the TOC feature from blogdown.

Also before relying on tries and test with GPT, look at the documentation to understand how a tool works.

Especially since 1.14, the default ouput format is now markdown for Hugo Goldmark processor to be applied, and so the TOC feature of the theme you are using to work. See news: Changelog • blogdown

Look at this page to understand the output format, and how to customize.

You can read also in blog Announcing blogdown v1.0

The book is a great place to look to understand how this works.

Hope it helps

1 Like

Hi, thanks for the answer! For anyone else reading, I have since learned you need to set options(blogdown.method = 'html') if using the approach suggested above:

output:
  blogdown::html_page:
    toc: true

Another approach is to modify the file per here, layouts/_default/single.html by modifying the article-content div:

    <div class="article-content">
      {{ if .Params.toc }}
      {{ .TableOfContents }}
      {{ end }}
      {{ .Content }}
    </div>

Then set toc: true in the yml for the page.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.