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 I had to add that script to my 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 part that feels like magic! I can now use this in all my html/nunjucks template files.
<!-- 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.