Eleventy filter to generate a Table of Contents in a template
npm install eleventy-plugin-tocThis Eleventy plugin will generate a TOC from page content using an Eleventy filter.
``jsol
{
tags: ['h2', 'h3', 'h4'], // which heading tags are selected headings must each have an ID attribute
wrapper: 'nav', // element to put around the root /ulol
wrapperClass: 'toc', // class for the element around the root /ulul
ul: false, // if to use instead of ol`
flat: false, // if subheadings should appear as child of parent or as a sibling
}
`sh`
npm i --save eleventy-plugin-toc
Your heading elements must have ids before this plugin will create a TOC. If there aren't ids on your headings, there will be no anchors for this plugin to link to.
I use markdown-it-anchor to add those ids to the headings: Eleventy config example
`js
// .eleventy.js
const markdownIt = require('markdown-it')
const markdownItAnchor = require('markdown-it-anchor')
module.exports = eleventyConfig => {
// Markdown
eleventyConfig.setLibrary(
'md',
markdownIt().use(markdownItAnchor)
)
// ... your other Eleventy config options
}
`
`js
// .eleventy.js
const pluginTOC = require('eleventy-plugin-toc')
module.exports = function (eleventyConfig) {
eleventyConfig.addPlugin(pluginTOC)
}
`
#### 3.1 You can override the default plugin options
`js`
module.exports = function (eleventyConfig) {
eleventyConfig.addPlugin(pluginTOC, {
tags: ['h2', 'h3'],
wrapper: 'div'
})
}
Because Eleventy only provides the content variable to layout templates (not to content files), you'll need to put this markup in a layout template:
`liquid`
{{ content }}
If you're using Nunjucks, include the safe filter:
`njk`
{{ content | safe }}
If you want to conditionally render a wrapper element, the filter will return undefined when no markup is generated:
`liquid`
{% if content | toc %}
{% endif %}
Pass a stringified JSON object (must be JSON.parse()-able) as an option for in your template. Because this is an object, you only need to include the key-value pairs you need to override; defaults will be preserved.
`liquid``
- [ ] Some tests would be nice