Notes // Configuring Nunjucks for Metalsmith

How to configure nunjucks to work with metalsmith.

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. The easiest way to add nunjucks template parsing is to use the metalsmith-layouts plugin. Metalsmith-layouts uses the JSTransformer node package to detect the format of template files via the filename extension. It is important to name your nunjucks files with the ".njk" file extension so that JSTransformer will know which transformer to use.

Pre-requisites

This article assumes that you have already installed Metalsmith and have setup a running Metalsmith build.js file. The installation step will be the same, but you would need to convert the build.js configuration below into a .json compatible format (check the metalsmith-layouts README)

Installing Packages

Install the metalsmith-layouts and jstransformer-nunjucks node packages:

$ npm install metalsmith-layouts jstransformer-nunjucks --save

# OR

$ yarn add metalsmith-layouts jstransformer-nunjucks

Configuring Metalsmith Layouts

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

// Include the layouts plugin
var layouts = require("metalsmith-layouts");

// ...
// Add metalsmith-layouts to the metalsmith plugin chain via the .use() method
// Change `directory` to the location where your nunjucks (.njk) files are stored
.use(layouts({
        directory: "./src/_layouts"
})

Set the directory parameter to wherever your layouts are stored and remember to name your templates with the .njk file extension so JSTransformer uses the nunjucks transformer.

Written by
Published
Email destin{AT}destinmoulton.com if you have any comments or questions.