forked from niceue/tpl.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
40 lines (37 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
var fs = require("fs");
function Compiler(html) {
html = html || '';
if (/\.(?=tpl|html)$/.test(html)) html = fs.readFileSync(html);
var begin = '<%',
end = '%>',
ecp = function(str){
return str.replace(/('|\\)/g, '\\$1').replace(/\r\n/g, '\\r\\n').replace(/\n/g, '\\n');
},
str = "var __='',echo=function(s){__+=s};with(_$||{}){",
blen = begin.length,
elen = end.length,
b = html.indexOf(begin),
e,
tmp;
while(b != -1) {
e = html.indexOf(end);
if(e < b) break; //出错后不再编译
str += "__+='" + ecp(html.substring(0, b)) + "';";
tmp = html.substring(b+blen, e).trim();
if( tmp.indexOf('=') === 0 ) { //模板变量
tmp = tmp.substring(1);
str += "typeof(" + tmp + ")!='undefined'&&(__+=" + tmp + ");";
} else { //js代码
str += tmp;
}
html = html.substring(e + elen);
b = html.indexOf(begin);
}
str += "__+='" + ecp(html) + "'}return __";
this.render = new Function("_$", str);
}
function tpl(html, data) {
var me = new Compiler(html);
return data ? me.render(data) : me;
};
module.exports = tpl;