DEV Community

Victor Camnerin
Victor Camnerin

Posted on • Originally published at victorcamnerin.com on

Parsing markdown in frontmatter for Eleventy templates, using filters

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);
};
Enter fullscreen mode Exit fullscreen mode
// .eleventy.jsconst 

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

module.exports = content => { 
  config.addFilter('markdownFilter', markdownFilter);
};
Enter fullscreen mode Exit fullscreen mode
<!-- Our template file -->
<div class="markdown-filter"> 
  {{ frontmatter-value | markdownFilter | safe }}
</div>
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)