JavaScript模板引擎使用
详细介绍参考 http://ejohn.org/blog/javascript-micro-templating/,这个模板引擎写得短小精悍,非常值得一看
1. [代码]tmpl.js
01 |
// Simple JavaScript Templating |
02 |
// John Resig - http://ejohn.org/ - MIT Licensed |
03 |
( function () { |
04 |
var cache = {}; |
05 |
06 |
this .tmpl = function tmpl(str, data) { |
07 |
|
08 |
// Figure out if we‘re getting a template, or if we need to |
09 |
// load the template - and be sure to cache the result. |
10 |
var fn = |
11 |
!/\W/.test(str) |
12 |
? |
13 |
cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) |
14 |
: |
15 |
// Generate a reusable function that will serve as a template |
16 |
// generator (and which will be cached). |
17 |
new Function( |
18 |
"obj" , "var p=[],print=function(){p.push.apply(p,arguments);};" + |
19 |
|
20 |
// Introduce the data as local variables using with(){} |
21 |
"with(obj){p.push(‘" + |
22 |
|
23 |
// Convert the template into pure JavaScript |
24 |
str |
25 |
.replace(/[\r\t\n]/g, " " ) |
26 |
.split( "<%" ).join( "\t" ) |
27 |
.replace(/((^|%>)[^\t]*)‘/g, "$1\r" ) |
28 |
.replace(/\t=(.*?)%>/g, "‘,$1,‘" ) |
29 |
.split( "\t" ) |
30 |
.join( "‘);" ) |
31 |
.split( "%>" ) |
32 |
.join( "p.push(‘" ) |
33 |
.split( "\r" ) |
34 |
.join( "\\‘" ) + |
35 |
"‘);}return p.join(‘‘);" |
36 |
); // Function ends |
37 |
38 |
// Provide some basic currying to the user |
39 |
return data ? fn(data) : fn; |
40 |
}; |
41 |
})(); |
2. [代码]index.html 跳至 [1] [2] [全屏预览]
01 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" |
02 |
"http://www.w3.org/TR/html4/loose.dtd" > |
03 |
<html xmlns= "http://www.w3.org/1999/xhtml" > |
04 |
<head> |
05 |
<meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" /> |
06 |
<title>JavaScript tmpl Use Demo</title> |
07 |
<script type= "text/javascript" src= "http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" ></script> |
08 |
<script src= "./tmpl.js" type= "text/javascript" ></script> |
09 |
<!-- 下面是模板user_tmpl --> |
10 |
<script type= "text/html" id= "user_tmpl" > |
11 |
<% for ( var i = 0; i < users.length; i++ ) { %> |
12 |
<li><a href= "<%=users[i].url%>" ><%=users[i].name%></a></li> |
13 |
<% } %> |
14 |
</script> |
15 |
<script type= "text/javascript" > |
16 |
// 用来填充模板的数据 |
17 |
var users = [ |
18 |
{ url: "http://baidu.com" , name: "jxq" }, |
19 |
{ url: "http://google.com" , name: "william" } |
20 |
]; |
21 |
|
22 |
$( function () { |
23 |
// 调用模板引擎函数将数据填充到模板获得最终内容 |
24 |
$( "#myUl" ).html(tmpl( "user_tmpl" , users)); |
25 |
}); |
26 |
</script> |
27 |
</head> |
28 |
<body> |
29 |
<div> |
30 |
<ul id= "myUl" > |
31 |
</ul> |
32 |
</div> |
33 |
</body> |
34 |
</html> |
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。