-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
53 lines (43 loc) · 1.31 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var nunjucks = require('nunjucks');
var path = require('path');
var debug = require('debug')('koa-nunjucks-promise');
module.exports = function (root, opts) {
var basePath = path.dirname(module.parent.filename);
if (typeof root === 'object') {
opts = root;
root = opts.root || basePath;
} else if (!root) {
root = basePath;
}
root = path.resolve(basePath, root);
opts = opts || {};
var env = nunjucks.configure(root, opts);
var ext = opts.ext || 'html';
var filters = opts.filters || {};
Object.keys(filters).forEach(f => {
env.addFilter.apply(env, [f].concat(filters[f]));
});
var globals = opts.globals || {};
Object.keys(globals).forEach(g => {
env.addGlobal(g, globals[g]);
});
return function (ctx, next) {
if (ctx.render) return next();
ctx.render = function (view, locals) {
locals = locals || {};
var state = ctx.state || {};
var context = Object.assign({}, state, locals);
debug('render %s with %j', view, context);
return new Promise(function (resolve, reject) {
var name = view + '.' + ext;
env.render(name, context, function (err, res) {
if (err) return reject(err);
ctx.body = res;
ctx.type = 'text/html';
resolve();
});
});
};
return next();
}
};