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?
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.
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.
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>
- 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">
- 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 4 years ago · Edit answerI 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 a year ago · Edit answerIs it possible to make the ToC conditional? Possible using something like this?
{{metadata.toc}}
<div class="js-toc" ></div>
{{/metadata.toc}}
Answered a year ago ·
Edit answer
Absolutely! Just add something like this to the metadata section of the specific posts and pages:
toc: yes
Answered a year ago ·
Edit answer