<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>引擎模版使用</title><scripttype="text/javascript"src="template.js"></script><scripttype="text/javascript">
window.onload=function(){var data ={
title :'小孩資訊',
stu :["小紅",'小星','無名','媛媛']}//引數1:下面的id名//引數2:需要渲染的資料//結果:生成靜態的頁面片段var html =template('templt',data);
document.getElementById("box").innerHTML =html;}</script><scripttype="text/html"id="templt"><!-- type格式: text/html ; id名自取 --><!--{{varName}}:中存放資料 --><h1>{{title}}</h1><!-- 迴圈判斷:判斷stu是否存在
使用each迴圈
-->{{if stu}}{{each stu as value i}}<div>{{value}}</div>{{/each}}{{/if}}</script></head><body><divid="box"></div></body></html>
示例程式碼(轉義與不轉義)
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>引擎模版使用</title><scripttype="text/javascript"src="template.js"></script></head><body><divid="content"></div><scriptid="test"type="text/html">{{if isAdmin}}<h1>{{title}}</h1><ul>{{each list as value i}}<li>索引 {{i +1}}:{{value}}</li>{{/each}}</ul>{{/if}}<p>不轉義:{{#strs}}</p><p>預設轉義:{{strs}}</p></script><script>// isAdmin:更加靈活,可以根據使用者身份來看是否可以獲取當前許可權var data ={
title:'基本例子',
isAdmin:true,
list:["文藝","攝影","部落格","電影"]}var html =template('test',data);var desc ={
strs:"<span style='color:#F00'>hello world!</span>"}
document.getElementById("content").innerHTML =html+template('test',desc);</script></body></html>
在js中存入模版
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>引擎模版使用</title><scripttype="text/javascript"src="template.js"></script></head><body><h1>在JavaScript中存放模版</h1><divid="content"></div><script>var source ='<ul>'+'{{each list as value i}}'+'<li>索引 {{i + 1}} :{{value}}</li>'+'{{/each}}'+'</ul>';//compile : 用模版生成新的函式//render :渲染傳入的引數,然後輸出靜態標籤內容var render = template.compile(source);var html =render({
list:["文藝","攝影","部落格","電影"]});
document.getElementById("content").innerHTML =html;</script></body></html>
嵌入子模板
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>引擎模版使用</title><scripttype="text/javascript"src="template.js"></script></head><body><divid="content"></div><scriptid="test"type="text/html"><h1>{{title}}</h1>{{include 'child'}}</script><scripttype="text/html"id="child"><ul>{{each list as value i}}<li>索引 {{i +1}}:{{value}}</li>{{/each}}</ul></script><script>var data ={
title:'嵌入子模板',
list:["文藝","攝影","部落格","電影"]}
document.getElementById("content").innerHTML =template('test',data);</script></body></html>