Blog // Configuring Nunjucks for Metalsmith

By Destin Moulton on March 9, 2017

    Metalsmith and Nunjucks

    This website is statically generated using Metalsmith. Metalsmith is a plugin based static site generator for Node. Metalsmith includes very little out-of-the-box functionality. It expects you to add functionality through the build pipeline via plugins and the .use(...) method.

    Nunjucks is an easy-to-use template engine, but like all Metalsmith functionality it must be added as a plugin. There are two popular plugins that can be used to run Nunjucks in the Metalsmith build chain: metalsmith-layouts and metalsmith-in-place. I decided to use metalsmith-layouts as I already had my Metalsmith build sequence configured, and adding the metalsmith-layouts step seemed easier than using metalsmith-in-place. metalsmith-in-place is definitely worth a look if you are starting a new project.

    This article assumes that you have already installed Metalsmith and have setup a running Metalsmith build file (javascript not json)

    Installing Nunjucks

    Install Nunjucks via npm:

    $ npm install nunjucks --save

    Install the metalsmith-layouts plugin:

    $ npm install metalsmith-layouts --save

    Configuring Nunjucks

    Inside the main metalsmith build file (ie index.js)...

    var layouts = require('metalsmith-layouts');
    var nunjucks = require('nunjucks');
    nunjucks.configure(['./src/_layouts'], {watch: false})
    // Later when you define your metalsmith layout engine...
            engine: 'nunjucks',
            directory: './src/_layouts'

    Set the directory parameter to wherever your layouts are stored.

    You might wonder why the nunjucks.configure(...) line has a {watch: false} option. Nunjucks will give a "path not found" error if you don't set this option.

    Related Information