javascript - Sharing nunjucks filters across node and browser -
i trying find way filter works on both side.
here code have on node :
var env = nunjucks.configure(__dirname + '/../templates', { express: app }); env.addfilter('date', function(str){ return 'ok'; });
and on browser side :
var env = new nunjucks.environment(); env.addfilter('date', function(str){ return 'ok'; });
i have filter in place available in these 2 different environments don't find solution so.
on client side using nunjucks-slim version. templates precompiled using gulp.
thanks !
you put filters in separate file/module, pass env in argument.
eg.
/** * @param env nunjucks environment */ function(env){ env.addfilter('fancy', function(input){ return 'fancy ' + input }); env.addfilter(...); return env; }
you use umd wrapper (https://github.com/umdjs/umd) make compatible both browser , server. finished wrapper might this:
// custom_filters.js (function (root, factory) { if (typeof define === 'function' && define.amd) { // amd. register anonymous module. define([], factory); } else if (typeof exports === 'object') { // node. not work strict commonjs, // commonjs-like environments support module.exports, // node. module.exports = factory(); } else { // browser globals (root window) root.custom_filters = factory(); } }(this, function () { // return value define module export. return function(env){ env.addfilter('fancy', function(input){ return 'fancy ' + input }); return env; }; }));
then use this:
node:
var env = nunjucks.configure(__dirname + '/../templates', { express: app }); require('./path/to/custom_filters')(env);
browser (globals):
var env = new nunjucks.environment(); window.custom_filters(env);
browser (amd):
define( ['nunjucks', 'path/to/custom_filters'], function(nunjucks, custom_filters){ var env = new nunjucks.environment(); return custom_filters(env); } );
Comments
Post a Comment