Search code examples
javascriptnunjucks

Custom filters for Nunjucks in Browser


So I added just plain via script tag this script here.

var env = new nunjucks.Environment();

// async filters must be known at compile-time
env.addFilter('asyncFilter', function(val, cb) {
  // do something
  return "test"
}, true);

In my template I then have

{{ item.opendays | asyncFilter }}

The error I get in the Chrome console:

Uncaught Template render error: (node/yummy/www/js/templates/restaurant.overview.html)
  Error: filter not found: asyncFilter 

Probably something really simple, but I just can't get it to work.

And here is the code I use for rendering:

 items = nunjucks.render(Config.rootPath + 'js/templates/restaurant.overview.html', {items: data});

Solution

  • You are not using the environment you just created and set up.

    items = env.render(Config.rootPath + 'js/templates/restaurant.overview.html', {
      items: data
    });
    

    That is, env.render() instead of nunjucks.render().