Parsing markdown in frontmatter for Eleventy templates, using filters

- 3 min read

Tags that this post has been filed under.

I encountered an interesting challenge the other day. I have a client project where I'm using Eleventy for my site generation. On of the collections (basically a set of pages generated during build-time from markdown files) would include multiple frontmatter values containing markdown. However, these would not be correctly parsed when added to the template file. So I thought it would be a perfect use case for a template filter.

So, first of all, I created a new file with my filter.

// markdown-filter.js

const MarkdownIt = require('markdown-it');

module.exports = content => {
const md = new MarkdownIt({
html: true
});

return md.render(content);
};
// .eleventy.js

const markdownFilter = require('[ path to your file ]/markdown-filter.js');

module.exports = content => {
config.addFilter('markdownFilter', markdownFilter);
};
<!-- Our template file -->

<div class="markdown-filter">
{{ frontmatter-value | markdownFilter | safe }}
</div>

Combining it with Eleventys safe filter we now have a solid way of parsing markdown in values created in frontmatter.