11ty / eleventy

A simpler site generator. Transforms a directory of templates (of varying types) into HTML.
https://www.11ty.dev/
MIT License
17.19k stars 494 forks source link

Using Nunjucks extensions from NPM? #884

Closed pbowyer closed 4 years ago

pbowyer commented 4 years ago

The 11ty documentation for writing our own Nunjucks tags is good. However there's a number of pre-written tags on NPM and I was wondering if we can use those (e.g. https://www.npmjs.com/package/nunjucks-markdown)?

I cannot work out how to get hold of nunjucksEngine in my .eleventy.js config file (the parameter that's passed to any custom Nunjucks tag I write in that file), which is needed to register the package. Can it be done?

pbowyer commented 4 years ago

I solved it by adding the following to my .eleventy.js config:

const markdownIt = require("markdown-it");

module.exports = function(eleventyConfig) {
    let mdIt = markdownIt({
        html: true,
        breaks: true,
        linkify: true,
        // Enable some language-neutral replacement + quotes beautification
        typographer:  false,

        // Double + single quotes replacement pairs, when typographer enabled,
        // and smartquotes on. Could be either a String or an Array.
        //
        // For example, you can use '«»„“' for Russian, '„“‚‘' for German,
        // and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
        quotes: '“”‘’',
    });
    eleventyConfig.setLibrary("md", mdIt);

    eleventyConfig.addPairedShortcode("markdown", function(content) {
        return mdIt.render(content);
    });

    return {
        // Your normal return options
    };
};

This was adapted from code I found in https://github.com/11ty/11ty-website/blob/master/.eleventy.js