Add a Table of Contents to each post?

I would like to add a TOC (table of contents) to each post on my blog. What is the best way to accomplish this?

1 replies

Here's a specfic guide to adding a Table of Contents to each post on the Diary template, but it can be adapted to other templates too.

  1. Make sure you have an editable template – this can be done by 'forking' one of the base templates on the Templates page. The following instructions will assume you are using the Diary template

  2. Open your template and add the following to your template's footer.html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.min.js"></script>
<script>tocbot.init({
  // Where to render the table of contents.
  tocSelector: '.js-toc',
  // Where to grab the headings to build the table of contents.
  contentSelector: '.entry',
  // Which headings to grab inside of the contentSelector element.
  headingSelector: 'h1, h2, h3',
  // For headings inside relative or absolute positioned containers within content.
  hasInnerContainers: true,
});
</script>
  1. Add the following to your template's head.html file, inside the <head> ... </head> tags:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.css">
  1. Add the following to your template's entry.html, right after line 7, before line 8:
<div class="js-toc" ></div>

Please let me know if you have any questions about the implementation of this.

Answered 2 years ago · Improve this answer

Markdown allowed
Question or feedback?
Contact us

Tags

developers 45 questions bug 21 questions posts 20 questions templates 14 questions resolved 10 questions how 9 questions meta 9 questions metadata 8 questions request 7 questions markdown 6 questions More tags →
Subscribe for changes
RSS Feed of latest questions