引言
doT.js可以更好的在html端使用json数据。
{{ }} for evaluation 模板标记符
{{= }} for interpolation 输出显示,默认变量名叫it
{{! }} for interpolation with encoding 编码后输出显示
{{? }} for conditionals 条件分支,if条件的简写
{{~ }} for array iteration 遍历数组
使用
引入js
<script type="text/javascript" src="../script/doT.min.js"></script>
<!-- jquery 移动端替代品 -->
<script type="text/javascript" src="../script/zepto.min.js"></script>
<!--<script type="text/javascript" src="../script/jquery.min.js"></script>-->
功能点
1.for interpolation 赋值
格式:
{{= }}
数据源:
{"name":"Jake","age":31}
区域:
<div id="interpolation"></div>
模板:
<script id="interpolationtmpl" type="text/x-dot-template">
<div>Hi {{=it.name}}!</div>
<div>{{=it.age || ''}}</div>
</script>
调用方式:
var dataInter = {"name":"Jake","age":31};
var interText = doT.template($("#interpolationtmpl").text());
$("#interpolation").html(interText(dataInter));
2.for evaluation for in 循环
格式:
{{ for var key in data { }}
{{= key }}
{{ } }}
数据源:
{"name":"Jake","age":31,"interests":["basketball","hockey","photography"],"contact":{"email":"jake@xyz.com","phone":"999999999"}}
区域:
<div id="evaluation"></div>
模板:
<script id="evaluationtmpl" type="text/x-dot-template">
{{ for(var prop in it) { }}
<div>KEY:{{= prop }}---VALUE:{{= it[prop] }}</div>
{{ } }}
</script>
调用方式:
var dataEval = {"name":"Jake","age":31,"interests":["basketball","hockey","photography"],"contact":{"email":"jake@xyz.com","phone":"999999999"}};
var evalText = doT.template($("#evaluationtmpl").text());
$("#evaluation").html(evalText(dataEval));
3.for array iteration 数组
格式:
{{~data.array :value:index }}
...
{{~}}
数据源:
{"array":["banana","apple","orange"]}
区域:
<div id="arrays"></div>
模板:
<script id="arraystmpl" type="text/x-dot-template">
{{~it.array:value:index}}
<div>{{= index+1 }}{{= value }}!</div>
{{~}}
</script>
调用方式:
var dataArr = {"array":["banana","apple","orange"]};
var arrText = doT.template($("#arraystmpl").text());
$("#arrays").html(arrText(dataArr));
4.for conditionals 条件
格式:
{{? }} if
{{?? }} else if
{{??}} else
数据源:
{"name":"Jake","age":31}
区域:
<div id="condition"></div>
模板:
<script id="conditionstmpl" type="text/x-dot-template">
{{? it.name }}
<div>Oh, I love your name, {{=it.name}}!</div>
{{?? !it.age === 0}}
<div>Guess nobody named you yet!</div>
{{??}}
You are {{=it.age}} and still dont have a name?
{{?}}
</script>
调用方式:
var dataCondition = {"age":31};
var conText = doT.template($("#conditionstmpl").text());
$("#condition").html(conText(dataCondition));
本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/5945263.html,如需转载请自行联系原作者