-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate_engine.js
58 lines (57 loc) · 1.3 KB
/
template_engine.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
/**
* 简易html模板
*
* @example
* html:
* <div id='TPL'>
* <? var data = this.data;?>
* <? if(data.a == 0) ?>
* <span>
* <?=data.a?>
* </span>
* <? } else { ?>
* <div>
* <?=data.b?>
* </div>
* <? } ?>
* </div>
*
* js:
* var htmlStr = parse(document.getElementById('TPL').innerHTML, {a : 0, b : 12});
*
*/
var cache = {};
function parse(str, data){
if (!cache[str] ){
var tpl = document.getElementById(str).innerHTML
tpl = tpl
.replace(/[\r\t\n]/g, " ")
.split("<\?").join("\t")
.replace(/((^|\?>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)\?>/g, "',$1,'")
.split("\t").join("');")
.split("\?>").join("p.push('")
.split("\r").join("\\'")
try{
cache[str] = new Function("",
"var p=[];p.push('" + tpl + "');return p.join('');");
}catch(e){
if (console){
console.log(e)
console.log(tpl)
}
}
}
var fn = cache[str]
if (data){
try{
return fn.apply( data )
}catch(e){
if (console){
console.log(e)
console.log(data)
}
}
}else
return fn();
}