JavaScript模板引擎用法实例
本文实例讲述了JavaScript模板引擎用法。分享给大家供大家参考。具体如下:
这里介绍的这个模板引擎写得短小精悍,非常值得一看
tmpl.js文件如下:
//SimpleJavaScriptTemplating
//JohnResig-http://ejohn.org/-MITLicensed
(function(){
varcache={};
this.tmpl=functiontmpl(str,data){
//Figureoutifwe'regettingatemplate,orifweneedto
//loadthetemplate-andbesuretocachetheresult.
varfn=
!/\W/.test(str)
?
cache[str]=cache[str]||tmpl(document.getElementById(str).innerHTML)
:
//Generateareusablefunctionthatwillserveasatemplate
//generator(andwhichwillbecached).
newFunction(
"obj","varp=[],print=function(){p.push.apply(p,arguments);};"+
//Introducethedataaslocalvariablesusingwith(){}
"with(obj){p.push('"+
//ConvertthetemplateintopureJavaScript
str
.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("\\'")+
"');}returnp.join('');"
);//Functionends
//Providesomebasiccurryingtotheuser
returndata?fn(data):fn;
};
})();
index.html文件如下:
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>JavaScripttmplUseDemo</title>
<scripttype="text/javascript"src="js/jquery.min.js"></script>
<scriptsrc="./tmpl.js"type="text/javascript"></script>
<!--下面是模板user_tmpl-->
<scripttype="text/html"id="user_tmpl">
<%for(vari=0;i<users.length;i++){%>
<li><ahref="<%=users[i].url%>"><%=users[i].name%></a></li>
<%}%>
</script>
<scripttype="text/javascript">
//用来填充模板的数据
varusers=[
{url:"http://baidu.com",name:"jxq"},
{url:"http://google.com",name:"william"}
];
$(function(){
//调用模板引擎函数将数据填充到模板获得最终内容
$("#myUl").html(tmpl("user_tmpl",users));
});
</script>
</head>
<body>
<div>
<ulid="myUl">
</ul>
</div>
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。