doT.js github地址:
doT.js 官方站点
实例1:简单
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="../../doT.js"></script>
<script type="text/javascript" src="http://hbjltv.com/static/js/jquery-1.11.1.js"></script>
</head>
<body>
<div id="interpolationtmpl">
<div>Hi {{=it.name}}!</div>
<div>{{=it.age || ''}}</div>
</div>
<hr/>
<div id="interpolation"></div>
<script type="text/javascript">
var dataInter = {"name": "Jake", "age": 31};
var interText = doT.template($("#interpolationtmpl").html());
$("#interpolation").html(interText(dataInter));
</script>
</body>
</html>
执行结果:
实例二:条件推断
<body>
<div id="conditionstmpl">
{{?
!it.name }}
<div> 你还没有名字</div>
{{?? }}
<div>Oh, I love your name, {{=it.name}}!</div>
{{?
}}
</div>
<hr/>
<div id="condition"></div>
<script type="text/javascript">
var dataEncode = {"name": "黄威", "age": 31};
var interText = doT.template($("#conditionstmpl").html());
$("#condition").html(interText(dataEncode));
</script>
</body>
执行结果:
if条件推断 还有另外一种写法:
<body>
<div id="conditionstmpl">
{{ if(!it.name){ }}
<div> 你还没有名字</div>
{{ } else { }}
<div>Oh, I love your name, {{=it.name}}!</div>
{{ } }}
</div>
<hr/>
<div id="condition"></div>
<script type="text/javascript">
var dataEncode = {"name": "", "age": 31};
var interText = doT.template($("#conditionstmpl").html());
$("#condition").html(interText(dataEncode));
</script>
</body>
实例三:循环+条件推断
<body>
<div id="evaluationtmpl">
{{ for(var prop in it) { }}
{{? typeof it[prop]=='object' }}
<div style="font-weight: bold;" >KEY:{{= prop }}---VALUE:</div>
{{ for(var prop2 in it[prop]) { }}
<div style="margin-left: 20px;" >key:{{= prop2 }}---value:{{= it[prop][prop2] }}</div>
{{ } }}
{{?
? }}
<div>KEY:{{= prop }}---VALUE:{{= it[prop] }}</div>
{{?
}}
{{ } }}
</div>
<hr/>
<div id="evaluation"></div>
<script type="text/javascript">
var dataEval = {
"name": "Jake",
"age": 31,
"interests": ["basketball", "hockey", "photography"],
"contact": {"email": "jake@xyz.com", "phone": "999999999"}
};
var evalText = doT.template($("#evaluationtmpl").html());
$("#evaluation").html(evalText(dataEval));
</script>
</body>
执行结果:
普通循环(不是foreach)
<script id="cuslist" type="text/x-dot-template">
{{ for(var prop in it){ }}
<table>
{{? typeof it[prop]['appName']=='object' }}
<tr > <td rowspan="{{=it[prop]['appName'].length}}" >{{=it[prop]['cusName']}}</td>
<td >{{=it[prop]['appName'][0]}}</td>
</tr>
{{ for(var prop2=1;prop2 <it[prop]['appName'].length; prop2++ ){ }}
<tr><td >{{=it[prop]['appName'][prop2]}}</td></tr>
{{ } }}
{{?
? }}
<tr><td >{{=it[prop]['cusName']}}</td><td >{{=it[prop]['appName']}}</td></tr>
{{?
}}
</table>
{{ } }}
</script>
源代码下载地址:
doT 源代码及实例
说明:
1,{{? typeof it[prop]==’object’ }} 表示条件推断,结束标签是{{?}}
2, {{?? }}是条件推断的else
3,{{ 和{{? 中均能够使用原生的js语法,如for,typeof 等
4,模板并非一定要放在script标签中,也能够放在隐藏的div标签中
本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5138803.html,如需转载请自行联系原作者