-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
77 lines (60 loc) · 1.95 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';
const nunjucks = require('nunjucks');
const { resolve, dirname, isAbsolute } = require('path');
const debug = require('debug')('koa-nunjucks-next');
const filterWrapper = filter => {
return (...args) => {
const callback = args.pop();
Promise.resolve(filter(...args)).then(
val => callback(null, val),
err => callback(err, null)
);
};
};
const isAsyncFn = fn => {
return fn && fn.constructor && [ 'GeneratorFunction', 'AsyncFunction' ].indexOf(fn.constructor.name) !== -1;
};
module.exports = function(root = 'views', option = {}) {
if (typeof root === 'object') {
option = root;
root = option.root || 'views';
}
if (!isAbsolute(root)) {
root = resolve(dirname(module.parent.filename), root);
}
const env = nunjucks.configure(root, option);
const { extname = 'html', extensions = {}, filters = {}, globals = {} } = option;
Object.keys(extensions).forEach(extensionKey => {
env.addExtension(extensionKey, extensions[extensionKey]);
});
Object.keys(filters).forEach(filterKey => {
const filterFn = filters[filterKey];
if (isAsyncFn(filterFn)) {
env.addFilter(filterKey, filterWrapper(filterFn), true);
} else {
env.addFilter(filterKey, filterFn);
}
});
Object.keys(globals).forEach(globalKey => {
env.addGlobal(globalKey, globals[globalKey]);
});
return (ctx, next) => {
if (ctx.render) return next();
ctx.render = (view, context = {}, isString = false) => {
const method = isString ? 'renderString' : 'render';
const template = isString ? view : `${view}.${extname}`;
context = Object.assign({}, ctx.state, context);
debug('render %s with %j', template, context);
return new Promise((resolve, reject) => {
env[method](template, context, (err, res) => {
if (err) {
return reject(err);
}
ctx.body = res;
resolve();
});
});
};
return next();
};
};