-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.js
66 lines (56 loc) · 1.63 KB
/
template.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
const fs = require('fs');
const path = require('path');
const sep = path.sep;
class Template {
constructor(config) {
var self = this;
self.config = config ? config : {};
self.config.baseDir = self.config.baseDir ? self.config.baseDir : '.';
self.config.extName = self.config.extName ? self.config.extName : '.html';
self.tmpl = require('blueimp-tmpl');
self.tmpl.load = function (id) {
var filename = `${process.cwd()}${sep}${self.config.baseDir}${sep}${id}${self.config.extName}`;
// console.log('Loading ' + filename);
var result;
try {
result = fs.readFileSync(filename, 'utf8');
} catch (e) {
console.log(e);
result = `Error: Loading Template ${id}${self.config.extName} has failed.`;
}
return result;
};
}
renderTemplate(id, data) {
data = data ? data : {};
return this.tmpl(id, data);
}
render(id, data) {
return new Promise((resolve, reject)=>{
try {
var result = this.renderTemplate(id, data);
resolve(result);
} catch (e) {
reject(new Error(`Error: Loading Template ${id}${this.config.extName} has failed.\n` + e.stack));
}
});
}
renderResponse(response, id, data) {
return this.render(id, data).then((result)=>{
response.end(this.renderTemplate(id, data));
return result;
}).catch((e)=>{
response.statusCode = 500;
response.write(e.stack);
response.end();
// return Promise.reject(e);
return e;
});
}
renderAsFunction() {
return (id, data) => this.render(id, data);
}
}
module.exports = {
Template,
};