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
原文地址:https://www.cnblogs.com/aten/p/9572130.html
时间: 2024-10-24 01:02:06