本文介紹了template.js前端模板引擎使用,分享給大家,具體如下:
下載地址:https://github.com/yanhaijing/template.js
作者編寫的文檔:https://github.com/yanhaijing/template.js/blob/master/README.md
源碼學習
默認的開始標簽和結(jié)束標簽分別是:
快速上手
編寫模板
使用一個type=”text/html”的script標簽存放模板,或者放到字符串中:
<script id="tpl" type="text/html"><ul> <%for(var i = 0; i < list.length; i++) {%> <li><%:=list[i].name%></li> <%}%></ul></script>渲染模板
var tpl = document.getElementById('tpl').innerHTML;template(tpl, {list: [{name: "yan"},{name: "haijing"}]});輸出:
<ul> <li>yan</li> <li>haijing</li></ul>
轉(zhuǎn)義
<script id="tpl" type="text/html"> <table> <caption>for循環(huán)輸出兩次</caption> <%var test = '輸出自定義變量';%> <%for (var i = 0; i < 2; i++) {%> <tr><td><%=html%>默認</td><td><%=html%></td></tr> <tr><td><%:h=html>html轉(zhuǎn)義</td><td><%:h=html%></td></tr> <tr><td><%:=html>不轉(zhuǎn)義</td><td><%:=html%></td></tr> <tr><td><%:u=url>URI轉(zhuǎn)義</td><td><%:u=url%></td></tr> <tr><td>var</td><td><%:=test%></td></tr> <tr><td><%=test + 1>表達式</td><td><%=test + 1%></td></tr> <%if (true) {%> <tr><td>if</td><td>if 語句</td></tr> <%}%> <tr><td>分割線</td><td>------------------------------</td></tr> <%}%> </table> </script> <script src="../template.js"></script> <script> var html = template(document.getElementById('tpl').innerHTML, { url: 'http://yanhaijing.com?name=顏海鏡', html: '<div id="test">template.js "</div>' }); console.log(html); document.getElementById('wp').innerHTML = html; </script><script> template.config({sTag: '<#', eTag: '#>'}); var tpl1 = '<div><#:=name#></div>'; console.log('<##>:', template(tpl1, {name: '更改tag<##>'})); template.config({sTag: '{{', eTag: '}}'}); var tpl1 = '<div>{{:=name}}</div>'; console.log('{{}}:', template(tpl1, {name: '更改tag{{}}'})); template.config({sTag: '<%', eTag: '#>'}); var tpl1 = '<div><%:=name#></div>'; console.log('<%#>:', template(tpl1, {name: '不一致也可以哦,更改tag<%#>'})); template.config({sTag: '<%', eTag: '%>', compress: true}); var tpl1 = '<div>空格會被壓縮 空格 空格</div>'; console.log('compress:', template(tpl1, {})); template.config({sTag: '<%', eTag: '%>', escape: false}); var tpl1 = '<div>默認輸出不進行轉(zhuǎn)義<%=html%></div>'; console.log('escape:', template(tpl1, {html: '<div>html</div>'})); </script>
新聞熱點
疑難解答
圖片精選