Custom Filter confusion

613 views
Skip to first unread message

Christian Gloddy

unread,
Dec 2, 2013, 2:14:16 PM12/2/13
to nunj...@googlegroups.com
I'm attempting to create a custom filter per the instructions here:
http://jlongster.github.io/nunjucks/api#custom-filters

I'm using Nunjucks with Express and wrote the following:

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

var env = new nunjucks.Environment();
env.addFilter('formatdate', function(str, format) {
  return str;
});

When I try to access a page that uses the filter, I get:
Template render error: Error: filter not found: formatdate

My assumption is that this is because I need to pass that env to Express, but where is the appropriate place to do so?

James Long

unread,
Dec 2, 2013, 3:58:14 PM12/2/13
to Christian Gloddy, nunj...@googlegroups.com
The higher-level API (nunjucks.configure, etc) internally uses its own
Environment object, so you don't have to create your own. There might
be a way to clarify this in the examples deeper down in the docs. Just
don't create your own Env, and use the one returned by `configure`:

var env = nunjucks.configure('views', { ... });

env.addFilter('foo', function() {});
> --
> You received this message because you are subscribed to the Google Groups
> "Nunjucks" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to nunjucks+u...@googlegroups.com.
> For more options, visit https://groups.google.com/groups/opt_out.

Christian Gloddy

unread,
Dec 2, 2013, 4:38:34 PM12/2/13
to nunj...@googlegroups.com, Christian Gloddy
Perfect! That did the trick. Much thanks.
I simply a Moment.js' formatting abilities via a filter:

env.addFilter('formatdate', function(str, format) {
  return moment(str).format(format);
});

Might be a nice thing to have as one of the built-in filters:
http://momentjs.com
Reply all
Reply to author
Forward
0 new messages