Nunjucks and jsTransformer

When using Nunjucks with Metalsmith-in-place or Metalsmith-layouts we are doing so via the jstransformer-nunjucks plugin. In this case, to extend the Nunjucks environment we have to pass a configuration object to the Metalsmith plugins.

Currently jstransformer-nunjucks supports a path variable, filters and extensions.

This is how we would pass these configuration options to Nunjucks:

In our Metalsmith build file

const CaptureTag = require(“nunjucks-capture”);

const toUpper = text => text.toUpperCase();
const spaceToDash = text => text.replace(/\s+/g,-);
const templateConfig = {
    engineOptions: {
        path: __dirname + '/layouts',
        filters: {
            toUpper: toUpper,
            spaceToDash: spaceToDash
        extensions: {
            CaptureTag: new CaptureTag()

This example defines the path to the layout directory. Now all paths in our templates must be relative to this layout directory path.

We are also adding two filters: One that converts a string to upper case and a second one that replaces all spaces in a string with dashes.

Finally, we are extending Nunjucks with nunjucks-capture - a nunjucks port of the Liquid Capture tag, which will allow us to use a new capture tag like so:

{% set favorite_food = 'pizza' %}
{% set age = 35 %}

{% capture about_me -%}
I am {{ age }} and my favorite food is {{ favorite_food }}.
{%- endcapture %}

{{ about_me }}

This will result in

I am 35 and my favorite food is pizza.

Everything between the two tags is stored in a new variable as a string. Dynamic content, such as includes or loops, are evaluated before the variable is stored. This means you've captured the resulting content, not the templating.

Scroll to top