Your sites Log in Sign up Menu

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?


4 months ago, 4 replies   developers   toc   Improve this question

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 3 years ago · Improve this answer

I chose this solution, but I can add something. To avoid conflicts with the main "stylesheet" of the template, I changed its name to "stylesheet2".

If you want the table of contents immediately after the article title, add the code:

<div class="js-toc" ></div>

on line 23 (on the example of the Magazine template), immediately after the code:

<div class="entry pv0 w-80 b--black-10" >

But I chose something else for myself. To optionally add headers, I didn't do the last step. Instead, I add the code:

<div class="js-toc" ></div>

In the text itself, where I need it, for example, after the first paragraph and illustration. It works well.

Answered 7 months ago · Improve this answer

Is it possible to make the ToC conditional? Possible using something like this?

{{metadata.toc}}
    <div class="js-toc" ></div>
{{/metadata.toc}}
Answered 5 months ago · Improve this answer

Absolutely! Just add something like this to the metadata section of the specific posts and pages:

toc: yes
Answered 4 months ago · Improve this answer