1
- /*! tpl.js 0.3.0 , github.com/niceue/tpl.js */
1
+ /*! tpl.js 0.3.1 , github.com/niceue/tpl.js */
2
2
3
3
/* 类似于PHP的嵌入方式, 可以嵌入js语句
4
4
模板语法:
5
5
嵌入传入的变量: <#=xxx#> , 注意,xxx变量不能为javascript关键字
6
6
嵌入任意js语句:<#if(xxx){#> foo <#}else{#> bar <#}#>
7
+ 内置 echo() 和 include() 两个方法
8
+ <###>之间的内容会被跳过编译<###>
7
9
调用:
8
10
方式一(直接输出结果):tpl(template, data)
9
11
方式二(预编译,二次调用传入data):tpl(template)(data)
21
23
22
24
function compiler ( html ) {
23
25
html = html || '' ;
24
- if ( / ^ # \w + $ / . test ( html ) ) html = document . getElementById ( html . substring ( 1 ) ) . innerHTML ;
25
- var begin = tpl . begin ,
26
- end = tpl . end ,
27
- v = tpl . variable ,
28
- arg1 = v || "$" ,
29
- trim = function ( str ) {
26
+ if ( html . charAt ( 0 ) === '#' ) html = document . getElementById ( html . substring ( 1 ) ) . innerHTML ;
27
+ var trim = function ( str ) {
30
28
return str . trim ? str . trim ( ) : str . replace ( / ^ \s * | \s * $ / g, '' ) ;
31
29
} ,
32
30
ecp = function ( str ) {
33
31
return str . replace ( / ( ' | \\ | \r ? \n ) / g, '\\$1' ) ;
34
32
} ,
35
- str = "var " + arg1 + "=" + arg1 + "||this,__='',echo=function(s){__+=s},include=function(t,d){__+=tpl(t).call(d||" + arg1 + ")};" + ( v ?"" :"with($||{}){" ) ,
36
- blen = begin . length ,
37
- elen = end . length ,
38
- b = html . indexOf ( begin ) ,
39
- e ,
33
+ begin = tpl . begin ,
34
+ end = tpl . end ,
35
+ v = tpl . variable ,
36
+ arg1 = v || "$" ,
37
+ str = "var " + arg1 + "=" + arg1 + "||this,__='',___,\
38
+ echo=function(s){__+=s},\
39
+ include=function(t,d){__+=tpl(t).call(d||" + arg1 + ")};" + ( v ?"" :"with($||{}){" ) ,
40
+ blen = begin . length , elen = end . length ,
41
+ b = html . indexOf ( begin ) , e ,
40
42
skip ,
41
43
tmp ;
42
44
43
45
while ( b != - 1 ) {
44
46
e = skip ? b + blen : html . indexOf ( end ) ;
45
47
if ( e < b ) break ; //出错后不再编译
46
-
47
48
str += "__+='" + ecp ( html . substring ( 0 , b ) ) + "';" ;
48
49
49
50
if ( skip ) {
53
54
tmp = trim ( html . substring ( b + blen , e ) ) ;
54
55
if ( '#' === tmp ) {
55
56
skip = 1 ;
56
- }
57
- else if ( tmp . indexOf ( '=' ) === 0 ) { //模板变量
57
+ } else if ( tmp . indexOf ( '=' ) === 0 ) { //模板变量
58
58
tmp = tmp . substring ( 1 ) ;
59
- str += "typeof ( " + tmp + ") !=='undefined'&&(__+=" + tmp + " );";
59
+ str += "___= " + tmp + ";typeof ___ !=='undefined'&&(__+=___ );" ;
60
60
} else { //js代码
61
- str += tmp + "; " ;
61
+ str += "\n" + tmp + "\n " ;
62
62
}
63
63
}
64
64
65
65
html = html . substring ( e + elen ) ;
66
66
b = html . indexOf ( begin + ( skip ? '#' + end : '' ) ) ;
67
67
}
68
68
str += "__+='" + ecp ( html ) + "'" + ( v ?";" :"}" ) + "return __" ;
69
- console . log ( str )
70
69
return new Function ( arg1 , str ) ;
71
70
}
72
71
73
72
//Browser global
74
73
window . tpl = tpl ;
75
74
//AMD and CMD (RequireJS, OzJS, curl, SeaJS ...)
76
75
typeof define === 'function' && define ( 'tpl' , [ ] , function ( ) { return tpl } ) ;
77
- } ) ( window ) ;
76
+ } ) ( this ) ;
0 commit comments