Eleventy: Markdown and Footnotes

The default Markdown plugin in the Eleventy Base Blog repo that I’m using as a basis doesn’t parse footnotes by default, so here’s a few notes on how I added support:

markdown-it-footnote

markdown-it-footnote does what it says on the tin, adds footnote support to the markdown-it parser that was already in place. I added it to my project:

npm install markdown-it-footnote --save

In .eleventy.js I required it, and then told my Markdown library to use it:

const markdownItFootnote = require("markdown-it-footnote");

…

let markdownLibrary = markdownIt({
    html: true,
    breaks: true,
    linkify: true,
    typographer: true,
  })
    .use(markdownItAnchor, {
      permalink: true,
      permalinkClass: "direct-link",
      permalinkSymbol: "#",
    })
    .use(markdownItFootnote);
eleventyConfig.setLibrary("md", markdownLibrary);

Styling the footnote link

That worked, except that it would render the footnote link with brackets, like: [1]. To change the output I had to override the footnote_caption() method, using the examples from the documentation. Note that the function in the module is render_footnote_caption() but it seems like the convention when overriding it is to drop the “render” part of that function name. So my override looks like this:

markdownLibrary.renderer.rules.footnote_caption = (tokens, idx) => {
  let n = Number(tokens[idx].meta.id + 1).toString();

  if (tokens[idx].meta.subId > 0) {
    n += ":" + tokens[idx].meta.subId;
  }

  return n;
};

In full, my Markdown configuration looks like this:

/* Markdown Overrides */
let markdownLibrary = markdownIt({
  html: true,
  breaks: true,
  linkify: true,
  typographer: true,
})
  .use(markdownItAnchor, {
    permalink: true,
    permalinkClass: "direct-link",
    permalinkSymbol: "#",
  })
  .use(markdownItFootnote);

markdownLibrary.renderer.rules.footnote_caption = (tokens, idx) => {
  let n = Number(tokens[idx].meta.id + 1).toString();

  if (tokens[idx].meta.subId > 0) {
    n += ":" + tokens[idx].meta.subId;
  }

  return n;
};
eleventyConfig.setLibrary("md", markdownLibrary);