_node.js
1.9 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
var fs = require('fs');
var path = require('path');
module.exports = function (template) {
var cacheStore = template.cache;
var defaults = template.defaults;
var rExtname;
// 提供新的配置字段
defaults.base = '';
defaults.extname = '.html';
defaults.encoding = 'utf-8';
function compileFromFS(filename) {
// 加载模板并编译
var source = readTemplate(filename);
if (typeof source === 'string') {
return template.compile(source, {
filename: filename
});
}
}
// 重写引擎编译结果获取方法
template.get = function (filename) {
var fn;
if (cacheStore.hasOwnProperty(filename)) {
// 使用内存缓存
fn = cacheStore[filename];
} else {
fn = compileFromFS(filename);
}
return fn;
};
function readTemplate (id) {
id = path.join(defaults.base, id + defaults.extname);
if (id.indexOf(defaults.base) !== 0) {
// 安全限制:禁止超出模板目录之外调用文件
throw new Error('"' + id + '" is not in the template directory');
} else {
try {
return fs.readFileSync(id, defaults.encoding);
} catch (e) {}
}
}
// 重写模板`include``语句实现方法,转换模板为绝对路径
template.utils.$include = function (filename, data, from) {
from = path.dirname(from);
filename = path.join(from, filename);
return template.renderFile(filename, data);
}
// express support
template.__express = function (file, options, fn) {
if (typeof options === 'function') {
fn = options;
options = {};
}
if (!rExtname) {
// 去掉 express 传入的路径
rExtname = new RegExp((defaults.extname + '$').replace(/\./g, '\\.'));
}
file = file.replace(rExtname, '');
options.filename = file;
fn(null, template.renderFile(file, options));
};
return template;
}