Scott Watermasysk Husband, Father, and KickoffLabs co-founder. Interests: basketball, bootstrapping, keyboards, training, and Building new things

Moving the Footnotes on Eleventy

Published:

Typically with Markdown, footnotes are found at the end of the content.

For my keyboard posts, I am using a nunjucks layout that looks a bit like this:

Example:

{{ content | safe }}
{% if soundTest %}
<div class="mb-2">
<h3 class="mb-2 text-2xl font-semibold text-center">Sound Profile</h3>
<p>{{soundTest}}</p>
</div>
{% endif %}

With this layout, my footnotes were not at the bottom of the page as you would typically expect (it went post content, footnotes, video, images).

With the help of this online regular expression tool, I put together the following transformer:

eleventyConfig.addTransform("move-footnotes", (content, outputPath) => {
if (outputPath && outputPath.endsWith(".html")) {
const footnoteRegex = /(<hr class="footnotes-sep">\n<section class="footnotes">[\s\S]+<\/section>)/m;
const newFootnoteLocationRegex = /<!--FOOTNOTES-->/;
let newLocation = content.match(newFootnoteLocationRegex);
let footnote = content.match(footnoteRegex);
if (newLocation && footnote) {
return content
.replace(footnoteRegex, "")
.replace(newFootnoteLocationRegex, footnote[0]);
}
}

return content;
});

What it does is check to see if there are indeed footnotes and that if a new location is defined to put them in. I did not want to try and guess where in the HTML to insert them, so I went with an HTML comment. If it finds this comment as well, it replaces it with the footnote HTML.

I am unfortunately executing both regular expressions twice, so there may be some other optimizations that can be made (such as declaring the regexes outside of the function). However, as far as I can tell for my site, there has not been a noticeable change in build speed.