Add a Markdown filter to Eleventy
17 Apr 2021 in TIL
I wanted to add markdown support to some elements in my front matter on the blog. To do this, I followed the example given in issue #658 on the Eleventy repo which uses markdown-it to add markdown support to any liquid template.
jsconst markdown = require("markdown-it")({html: true,breaks: true,linkify: true,});module.exports = function (eleventyConfig) {eleventyConfig.addFilter("markdown", function (rawString) {return markdown.render(rawString);});};
When I tried to render the title using <h1>{{ post.data.title | markdown }}</h1> my styling looked odd. This is due to the fact that markdown.render() wraps the content in a <p> tag automatically.
To prevent this, you can call markdown.renderInline which will not wrap the content in paragraph tags:
jsconst markdown = require("markdown-it")({html: true,breaks: true,linkify: true,});module.exports = function (eleventyConfig) {eleventyConfig.addFilter("markdown", function (rawString) {return markdown.renderInline(rawString);});};