Search code examples
javascriptexpressnunjucks

how to configure nunjucks for custom filters with express?


I was trying to add a custom filter with nunjucks following the docs. But running the code shows output -- Error: filter not found: my_filter_here

These are my configurations:

index.js

const express = require('express');
const nunjucks = require('nunjucks');

const port = 3000;
const app = express();

nunjucks.configure('views', {
  autoescape: true,
  express: app
})

app.set('view engine', 'html');

const env = new nunjucks.Environment();

env.addFilter('is_undefined', function(obj) {
  return typeof obj === 'undefined';
});

For rendering templates, I am using

res.render('register.html', {errors: errors});

in my template, I have set up like this:

{% if errors|is_undefined %}
  // do something
{% endif %}

And this is the error I am getting: Error: filter not found: is_undefined

I have searched s.o before posting this question and some answers indicated that I need to use env.render() that I previously added the filter to instead of res.render. How ever when I change it to so it does not render my html page. Any solution to get things right?

Thanks in advance. :)


Solution

  • According to doc: configure returns an Environment instance. Therefore

    const env = nunjucks.configure('views', {
      autoescape: true,
      express: app
    })
    
    env.addFilter('is_undefined', function(obj) {
      return typeof obj === 'undefined';
    });