Blog // Nunjucks Date Filter Metalsmith Configuration

JavaScript Promise API

By on

Nunjucks Date Filter

Nunjucks doesn't come with a built-in date format method. However, nunjucks-date-filter is a nunjucks filter that wraps moment.js into an easy to use Nunjucks compatible method.

This article assumes you have already configured Nunjucks to work with Metalsmith via the metalsmith-layouts plugin and the jstransformer-nunjucks package. Check out my Configuring Nunjucks for Metalsmith blog post if you want details on installing and configuring those packages.

Step One: Install the nunjucks-date-filter plugin:

$ npm install nunjucks-date-filter --save

# OR

$ yarn add nunjucks-date-filter

Step Two: Configure nunjucks-date-filter for Metalsmith

The nunjucks-date-filter README recommends using the Nunjucks Environment API to add filters. This instruction doesn't work with Metalsmith because the Env object is never applied to the Nunjucks instance. The metalsmith-layouts plugin use JSTransformers to perform template compilation. It has an engineOptions property to configure filters.

// Inside the metalsmith build.js file...
var layouts = require("metalsmith-layouts");
var dateFilter = require("nunjucks-date-filter");

// ...in the Metalsmith plugin .use() chain
.use(layouts({
    directory: "./src/_layouts",
    engineOptions: {
        filters: {
            date: dateFilter
        }
    }))

This adds a date(...) filter that can now be used in Nunjucks templates.

Using nunjucks-date-filter

Using the date filter in templates is simple. Call the date(...) filter and use the standard momentjs formatting rules to output the format that you desire.

Example custom date format using momentjs syntax:

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