Blog // Configuring Nunjucks for Metalsmith

By Destin Moulton on March 22, 2017

    Installing Nunjucks

    Installing Nunjucks via npm is easy.

    $ npm install nunjucks --save

    Configuring Nunjucks

    Nunjucks will give a "path not found" error if you don't configure nunjucks to not watch your layouts directory.

    var nunjucks = require('nunjucks');
    nunjucks.configure(['./src/_layouts'], {watch: false})
    // Later when you define your metalsmith layout engine...
            engine: 'nunjucks',
            directory: './src/_layouts',
            default: 'main.html',
            pattern: ["*/*/*html","*/*html","*html"]

    Adding a date Filter to Nunjucks

    In order to format dates in the blog I knew I would have to add a filter to Nunjucks.

    I found an easy to use moment.js date filter called nunjucks-date-filter built byPierre Cassat.

    The nunjucks-date-filter README recommends using the Nunjucks Environment api to add the filter. Unfortunately, this doesn't work with Metalsmith (the env object is never applied to the Nunjucks instance). Instead, you can directly use the Nunjucks global .addFilter() method to add a filter to the global Nunjucks instance.

    var dateFilter = require('nunjucks-date-filter');
    var metadata_debug = require('./metadata_debug');
    var image_processor = require("./image_processor");
    // Fix nunjucks path issue and add moment as date filter
    nunjucks.configure(['./src/_layouts'], {watch: false})
            .addFilter('date', dateFilter);

    Using the date filter in templates is simple. You can use the standard momentjs formatting rules to output the exact format that you desire.

    {{ publish_date | date("MMMM D, YYYY") }}

    Why I Chose Nunjucks

    Many Metalsmith tutorials show a preference for Handlebars as the template engine. I like mustache-esque templates, but I knew from experience that a "logic-less" engine wouldn't offer me enough flexibility for re-building my website using Metalsmith.

    Converting my existing site templates to Nunjucks was also easier than converting to Jade or Handlebars. This site was originally built using Laravel. Laravel's template engine is Blade. Blade and Nunjucks are similar enough that I was able to convert the original templates to Nunjucks without too much fuss.