Blog // Nunjucks Date Filter Metalsmith Configuration

By Destin Moulton on March 10, 2017

    Nunjucks Date Filter

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

    This article assumes you have already configured Nunjucks to work with Metalsmith. Check out my Configuring Nunjucks for Metalsmith blog post if you want to see how.

    Configuring nunjucks-date-filter for Metalsmith

    The nunjucks-date-filter README recommends using the Nunjucks Environment API to add the filter. Unfortunately, this doesn't work with Metalsmith because 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.

    Install the nunjucks-date-filter plugin:

    $ npm install nunjucks-date-filter --save
    

    Configure nunjucks-date-filter:

    // Inside the metalsmith build file...
    var dateFilter = require('nunjucks-date-filter');
    
    // ...after nunjucks.configure(...)
    nunjucks.addFilter('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 Information