.TableOfContents in Markdown

Hi all
I am trying to manually add table of contents to some of my posts. Hugo has a variable named .TableOfContents as seen here. Obviously I cannot directly use {{ .TableOfContents }} in markdown so I created a shortcode.

Let’s call it toc.html and it’s pretty simple:

{{ .TableOfContents }}

We get this error:

ERROR: 2016/03/27 error processing shortcode shortcodes/toc.html
ERR: template: shortcodes/toc.html:6:3: executing "shortcodes/toc.html" at <.TableOfContents>: 
TableOfContents is not a field of struct type *hugolib.ShortcodeWithPage

Ok, so we switch the template to:

{{ .Page.TableOfContents }}

No errors but no toc.

From my searches around the forum, it seems like a chicken and egg problem. The toc is generated from BlackFriday, so it is most probably empty before the markdown is completely processed.

I can easily use it in the template by adding {{ .TableOfContents }} and it correctly generates a toc. I just take the HTML and manually paste it in the page and remove the code in template and regenerate.

Another thing that comes into my mind is to add a new page parameter to the frontmatter named toc and then check it in the template and if it exists create a toc. However, the toc will be added before the {{ .Content }} and I want it just right after the <!--more--> tag like this post.

Am I missing something? Is there a much simpler way of doing this or ?


Currently no – but this is in the “wishlist” and I believe I created a Blackfriday issue about “sections support” at some point.

1 Like
1 Like

Thanks @bep. I think I will go with my manual way for now, a little bit of copy/pasting in the end is ok.