標籤:clear array 個人 pre eid style png bsp 代碼
doT.js是一個輕量簡單的模板輸出js. 下面介紹一下它的基本用法。
1.輸出 基本輸出:{{= }} 原樣輸出:{{! }}
<div id="info"></div> <script id="dot-template" type="text/x-dot-template"> <p>name:{{=it.name}}</p> <p>age:{{=it.age}}</p> <p>{{=it.html}}</p> <p>{{!it.html}}</p> </script> <script type="text/javascript"> var dataJSON = {"name": "AlanJ", "age": "20", "html": "<div style=‘background: #f00; height: 30px; line-height: 30px;‘>html元素</div>"}; var html = doT.template(document.getElementById("dot-template").text)(dataJSON); document.getElementById("info").innerHTML = html; </script>
2.判斷 if:{{? }} else if:{{??}}
<div id="info"></div> <script id="dot-template" type="text/x-dot-template"> <p>name:{{=it.name}}</p> <p>score:{{=it.score}}</p> {{? it.score < 60}} <p>不及格</p> {{?? it.score < 80}} <p>及格</p> {{??}} <p>優秀</p> {{?}} </script> <script type="text/javascript"> var dataJSON = {"name": "AlanJ", "score": "100"}; var html = doT.template(document.getElementById("dot-template").text)(dataJSON); document.getElementById("info").innerHTML = html; </script>
3.迴圈 for each {{~it :item:index}} {{~}} for in: {{for (var index in it){ }} {{ } }}
-------------------------------------for each---------------------------------------------- <ul id="info1"></ul> -------------------------------------for in---------------------------------------------- <ul id="info2"></ul> <script id="dot-template1" type="text/x-dot-template"> {{~it :item:index}} <li> <p>index:{{=index + 1}}</p> <p>name:{{=item.name}}</p> <p>age:{{=item.age}}</p> </li> {{~}} </script> <script id="dot-template2" type="text/x-dot-template"> {{for (var index in it){ }} <li> <p>index:{{=index + 1}}</p> <p>name:{{=it[index].name}}</p> <p>name:{{=it[index].age}}</p> </li> {{}}} </script> <script type="text/javascript"> var dataJSONArray = [{"name": "AlanJ", "age": "20"}, {"name": "Jack", "age": "40"}, {"name": "ClearLove", "age": "60"}]; var html1 = doT.template(document.getElementById("dot-template1").text)(dataJSONArray); document.getElementById("info1").innerHTML = html1; var html2 = doT.template(document.getElementById("dot-template2").text)(dataJSONArray); document.getElementById("info2").innerHTML = html2; </script>
4.partials (個人理解:部分拼接 ) 全:{{##def.snippet:{{#def.joke}}#}}{{#def.snippet}} 簡:{{#def.joke}}
<div id="info"></div> <script id="dot-template" type="text/x-dot-template"> <div>{{=it.name}}</div> {{##def.snippet: {{#def.joke}} #}} {{#def.snippet}}
{{#def.joke}} </script> <script type="text/javascript"> var dataJSON ={"name":"AlanJ"}; var defPart = {"joke":"<div>{{=it.name}} who?</div>"}; var html = doT.template(document.getElementById("dot-template").text, null, defPart)(dataJSON); document.getElementById("info").innerHTML = html; </script>
出處:https://0qingfeideyi0.iteye.com/blog/2274741
參考文檔:http://olado.github.io/doT/
原始碼:https://github.com/olado/doT
dot.js簡單入門