-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
65 lines (56 loc) · 1.71 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
const pug = require('pug');
const path = require('path');
function koaPug(app, viewDirOrOption = 'views', argNeedCache = false, argMethodname = 'render') {
let viewDir = 'views';
let needCache = false;
let methodName = 'render';
needCache = argNeedCache;
methodName = argMethodname;
if (Object.prototype.toString.call(viewDirOrOption) === '[Object Object]') {
const {
viewDir: optionViewDir,
needCache: optionNeedCache,
methodName: optionMethodName,
} = viewDirOrOption;
if (optionViewDir !== undefined) {
viewDir = optionViewDir;
}
if (optionNeedCache !== undefined) {
needCache = optionNeedCache;
}
if (optionMethodName !== undefined) {
methodName = optionMethodName;
}
} else if (typeof viewDirOrOption === 'string') {
viewDir = viewDirOrOption;
}
if (!app) {
throw new Error('app is required');
}
if (app.context[methodName]) {
console.log(`there is already methodName: ${methodName} on app.context, function just return`);
return;
}
if (process.env.NODE_ENV && process.env.NODE_ENV === 'production') {
needCache = true;
}
if (!needCache) {
app.context[methodName] = function (template, obj) {
this.body = pug.renderFile(
path.join(__dirname, '..', '..', viewDir, template),
Object.assign({}, this.state, obj)
);
};
return;
}
koaPug._cache_ = {};
app.context[methodName] = function (template, obj) {
if (!koaPug._cache_[template]) {
koaPug._cache_[template] = pug.compileFile(
path.join(__dirname, '..', '..', viewDir, template)
);
}
this.body = koaPug._cache_[template](Object.assign({}, this.state, obj));
};
}
module.exports = koaPug;