Skip to content

Advanced example with custom nunjucks filter

Kevin Van Lierde edited this page Dec 3, 2022 · 2 revisions

You can use @metalsmith/in-place with metalsmith's javascript API or the CLI. For this example we'll use the javascript API:

Install metalsmith and @metalsmith/in-place:

$ npm install metalsmith @metalsmith/in-place

Install appropriate jstransformers

In this case we're using nunjucks, so we'll also need to install jstransformer-nunjucks:

$ npm install jstransformer-nunjucks

Configure metalsmith

We'll create a build script and a file for @metalsmith/in-place to process:

./build.js

const metalsmith = require('metalsmith');
const inPlace = require('@metalsmith/in-place');

const toUpper = text => text.toUpperCase();

metalsmith(__dirname)
  .source('src')
  .destination('build')
  .use(inPlace({
    engineOptions: {
      filters: {
        toUpper: toUpper
      }
    }
  }))
  .build(error => {
    if (error) throw error;
  });

The custom nunjucks filter toUpper is defined as a function and then passed to jstransformer-nunjucks via the engineOptions option.

./src/index.njk

---
text: Some text in the frontmatter
---
<p>{{ text | toUpper }}</p>

Build

To build just run the build.js build script:

$ node build.js

Which will output the following file:

./build/index.html

<p>SOME TEXT IN THE FRONTMATTER</p>