Adding Custom Anchors to Headings in Markdown - Eleventy

Adding Custom Anchors to Headings in Markdown - Eleventy

Using 'markdown-it-anchors' and 'markdown-it-attrs' plugins

Anchors are nothing but id attributes applied to an element to link to it using href attribute internally on the same page.

By default, 11ty uses markdown-it library to parse markdown. But, it seems that by default, markdown-it doesn't support syntax for applying an id to a header element.

The syntax for applying a custom id to a header element in markdown is as follows:

## text {#id}

To make that syntax work, you need to create your own instance of markdown-it library and add two plugins, markdown-it-anchors and markdown-it-attrs.

The markdown-it-anchors plugin will apply a default id depending on the heading text automatically to every header element in our markup.

The markdown-it-attrs plugin will replace the default id with the custom id you specify.

Applying Custom Anchors

Install the required dependencies:

npm i markdown-it markdown-it-anchor markdown-it-attrs

Require them inside .eleventy.js file,

const markdownIt = require('markdown-it');
const markdownItAnchor = require('markdown-it-anchor');
const markdownItAttrs = require('markdown-it-attrs');

Create an instance of the markdown-it library inside the module.exports function.

eleventyConfig.setLibrary("md", markdownIt().use(markdownItAnchor)).use(markdownItAttrs)

You can also add some options such as:

let markdownItOptions = {
    html: true // you can include HTML tags
}

let markdownItAnchorOptions = {
    level: 2 // minimum level header -- anchors will only be applied to h2 level headers and below but not h1
}

eleventyConfig.setLibrary("md", markdownIt(markdownItOptions).use(markdownItAnchor, markdownItAnchorOptions).use(markdownItAttrs))

Now, if you do something like:

## Heading 1 {#head1}

In this case, head1 will be the id of this header element. You can link to this element by using #head1 as the href value. That's how you can add custom anchors to heading elements.

Applying Default Anchors

If you don't want a custom id and just want to keep the default id that's being applied to the element by the markdown-it-anchors plugin, then remove the markdown-it-attrs plugin and you will get a default anchor applied to the element.

eleventyConfig.setLibrary("md", markdownIt(markdownItOptions).use(markdownItAnchor, markdownItAnchorOptions))

That's all for now. Signing Off.

This post was originally published in Syntackle