Parsing markdown in frontmatter for Eleventy templates, using filters

- 2 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);
};

Then we have to add that script to our eleventy config file.

// .eleventy.js

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

module.exports = content => {
  config.addFilter('markdownFilter', markdownFilter);
};

And finally. The magic! We can use it in our html/nunjucks template file.

<!-- 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.