模板引擎doT.js介绍及如何判断对象为空、如何嵌套循环···

时间:2021-01-08 09:06:22

JS模板引擎像百度的baiduTemplate(百度)\artTemplate(腾讯)\juicer(淘宝)\doTtmplhandlebarseasyTemplateunderscoretemplate \ mustache \kissytemplate

doT.js 灵感来源于搜寻基于 V8 和 Node.js ,强调性能,最快速最简洁的 JavaScript 模板函数

引入 javascript 文件:

<script type="text/javascript" src="doT.js"></script>

doT.templateSettings - 默认编译设置

可以通过改变编译设置自定义 doT。这是默认设置:

doT.templateSettings = {
evaluate: /\{\{([\s\S]+?)\}\}/g,
interpolate: /\{\{=([\s\S]+?)\}\}/g,
encode: /\{\{!([\s\S]+?)\}\}/g,
use: /\{\{#([\s\S]+?)\}\}/g,
define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
varname: 'it',
strip: true,
append: true,
selfcontained: false
};

如果你想用自己的定界符,可以修改 doT.templateSettings 中的正则表达式。

这是默认的定界符列表:

{{ }}    用于求值(evaluation)
{{= }} 用于插值(interpolation)
{{! }} 用于编码求值(interpolation with encoding)
{{# }} 用于编译时求值/引入和局部模板(compile-time evaluation/includes and partials)
{{## #}} 用于编译时定义(compile-time defines)
{{? }} 条件语句(conditionals)
{{~ }} 数组迭代(array iteration)

调用方式:
var tmpText = doT.template(模板);
tmpText(数据源);

用法示例:

for 循环前判断循环的list是否为空

        <script id="invoiceListDot" type="text/x-dot-template">
{{? it.invoiceInfoDtos}}
{{ for(var prop=;prop
<it.invoiceInfoDtos.length
; prop++){ }}
<div class="{{ if(prop==0){}}invoice-infor {{ }else {}}no-invoice{{ }}}" data-index="{{= prop }}">
<span class="no-ivoice-icon"></span>
<span>普通发票</span>
<span class="ivo-margin">{{= it.invoiceInfoDtos[prop].content }}</span>
<span class="ivo-margin">{{= it.invoiceInfoDtos[prop].title }}</span>
<span class="ivo-margin">{{= it.invoiceInfoDtos[prop].address }}</span>
<span class="ivo-margin">{{= it.invoiceInfoDtos[prop].receiver }}</span>
<span class="ivo-margin">{{= it.invoiceInfoDtos[prop].phone }}</span>
</div>
{{ } }}
{{?}}
</script>

嵌套for循环的使用

(1)json数据结构:

var goods_list = {
"list": [
{
"id": "",
"name": "衣服",
"goods": [
{
"goods_id": "",
"name": "衣服1",
"price": "",
"logoimg": "http://image.diandodo.com/zhudianbao/Uploads/User/u1250000222/20160723/201607231342158687.png@250h_250w_1e_1c"
},
{
"goods_id": "",
"name": "衣服2",
"price": "",
"logoimg": "http://image.diandodo.com/zhudianbao/Uploads/User/u1250000222/20160723/201607231342158687.png@250h_250w_1e_1c"
}
]
},
{
"id": "",
"name": "鞋子",
"goods": [
{
"goods_id": "",
"name": "鞋子1",
"price": "",
"logoimg": "http://image.diandodo.com/zhudianbao/Uploads/User/u1250000222/20160723/201607231342158687.png@250h_250w_1e_1c"
},
{
"goods_id": "",
"name": "鞋子2",
"price": "",
"logoimg": "http://image.diandodo.com/zhudianbao/Uploads/User/u1250000222/20160723/201607231342158687.png@250h_250w_1e_1c"
}
]
}
]
};

(2)区域与页面的构建

    <div id="category-goods"></div>
<!-- 必须加上type="text/x-dot-template" -->
<script id="category-goods-tmpl" type="text/x-dot-template">
{{ for(var i=, catlen=it.length; i<catlen; i++) { }}
<div class="rxsp">
<div class="aui-pull-left"><h3> {{= it[i].name }} </h3></div>
<a class="aui-pull-right ">
查看更多
<span class="aui-iconfont aui-icon-right"></span>
</a>
</div> <div class="aui-list-item-inner">
<div class="aui-row aui-row-padded">
{{ for(var j=, goodslen=it[i]['goods'].length; j<goodslen; j++) { }}
<div class="aui-col-xs-6">
<img src="{{= it[i]['goods'][j].logoimg }}" onclick="openWin('goods_detail')">
<p class="tit">{{= it[i]['goods'][j].name }} </p>
<div class="aui-info" style="padding-top:0">
<div class="aui-info-item">
<span class="red">¥{{= it[i]['goods'][j].price }}<!-- <span class="jifen"> 积分1000</span></span> -->
</div>
</div>
</div>
{{ } }}
</div>
</div>
{{ } }}
</script>

(3)绑定到容器

    var evalText = doT.template($("#category-goods-tmpl").text());
$("#category-goods").html(evalText(goods));

宏的使用

<div class="content" id="serviceItem">
{{##def.spaceUnit:
{{? it.productPrice.policyInfo.storageUnit== }}K{{?? it.productPrice.policyInfo.storageUnit==}}M{{??
it.productPrice.policyInfo.storageUnit==}}G {{?? }}T {{? }}
#}} <div class="buy-list">
<ul>
<li class="buy-name">购买时长:</li>
<li class="buy-select"><p>{{=it.productPrice.userPeriod}}个月</p></li>
<li class="buy-unit"></li>
<li class="buy-state">预计到期时间:{{=it.productPrice.endTime}}</li>
</ul>
</div>
<div class="buy-list">
<ul>
<li class="buy-name">用户数:</li>
<li class="buy-select"><input name="userCount" onkeypress="eventUtil.onlyNumberKeyPress(event)"
type="text"></li>
<li class="buy-unit">人</li>
<li class="buy-state">用户单价 {{=it.productPrice.normalPriceDto.userPeriodPrice}}元/人
{{? it.productPrice.policyInfoDto.periodUnit== }} 年{{??
it.productPrice.policyInfoDto.periodUnit==}}月{{??
it.productPrice.policyInfoDto.periodUnit==}}天 {{?? }}单位未知 {{? }}
<span class="warning">(目前只支持200人以内的团队)</span></li>
</ul>
</div> <div class="buy-list">
<ul>
<li class="buy-name">扩容空间(所有):</li>
<li class="buy-select"><input name="expansion_storage"
onkeypress="eventUtil.onlyNumberKeyPress(event)" type="text"></li>
<li class="buy-unit">{{#def.spaceUnit}}</li>
<li class="buy-state">空间单价 {{=it.productPrice.normalPriceDto.storagePrice}}元/
{{#def.spaceUnit}}
</li>
</ul>
</div>
</div>

最常规用法{{=it.attr}}

数据源:{"name":"Jake","age":}
区域:<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":};
var interText = doT.template($("#interpolationtmpl").text());
$("#interpolation").html(interText(dataInter));

for evaluation for in 循环

格式:
{{ for var key in data { }}
{{= key }}
{{ } }} 数据源:{"name":"Jake","age":,"interests":["basketball","hockey","photography"],"contact":{"email":"jake@xyz.com","phone":""}} 区域:<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":,"interests":["basketball","hockey","photography"],"contact":{"email":"jake@xyz.com","phone":""}};
var evalText = doT.template($("#evaluationtmpl").text());
$("#evaluation").html(evalText(dataEval));

循环数组{{~}}

格式:
{{~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+ }}{{= value }}!</div>
{{~}}
</script>
调用方式:
var dataArr = {"array":["banana","apple","orange"]};
var arrText = doT.template($("#arraystmpl").text());
$("#arrays").html(arrText(dataArr));

条件渲染{{?}}{{??}},相当于原生的if else if

格式:
{{? }} if
{{?? }} else if
{{??}} else
数据源:{"name":"Jake","age":}
区域:<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 === }}
<div>Guess nobody named you yet!</div>
{{??}}
You are {{=it.age}} and still dont have a name?
{{?}}
</script>
调用方式:
var dataEncode = {"uri":"http://bebedo.com/?keywords=Yoga","html":"<div style='background: #f00; height: 30px; line-height: 30px;'>html元素</div>"};
var EncodeText = doT.template($("#encodetmpl").text());
$("#encode").html(EncodeText(dataEncode));

编码渲染{{!}},主要是为了防止代码注入以保障安全,如传入一个HTML片段或js片段,它会以字符串的形式渲染

数据源:{"uri":"http://bebedo.com/?keywords=Yoga"}
格式:
{{!it.uri}}
区域:<div id="encode"></div>
模板:
<script id="encodetmpl" type="text/x-dot-template">
Visit {{!it.uri}} {{!it.html}}
</script>
调用方式:
var dataEncode = {"uri":"http://bebedo.com/?keywords=Yoga","html":"<div style='background: #f00; height: 30px; line-height: 30px;'>html元素</div>"};
var EncodeText = doT.template($("#encodetmpl").text());
$("#encode").html(EncodeText(dataEncode));

支持共用模块定义{{##def.}}定义,{{#def.}}引用模块

数据源:{"name":"Jake","age":}
区域:<div id="part"></div>
模板:
<script id="parttmpl" type="text/x-dot-template">
{{##def.snippet:
<div>{{=it.name}}</div>{{#def.joke}}
#}}
{{#def.snippet}}
{{=it.html}}
</script>
调用方式:
var dataPart = {"name":"Jake","age":,"html":"<div style='background: #f00; height: 30px; line-height: 30px;'>html元素</div>"};
var defPart = {"joke":"<div>{{=it.name}} who?</div>"};
var partText = doT.template($("#parttmpl").text(), undefined, defPart);
$("#part").html(partText(dataPart));
//个人用例
window.onload = function () {
dotFunc = doT.template(document.getElementById("tmpl").innerHTML);
/*dotFunc = doT.template($("#tmpl").text()); //与上行等同*/
/*console.log('dotFunc', dotFunc);*/
/*printOrders("[{SerialNumber:'01234567891'}]");*/
/* printOrders("[{SerialNumber:'01234567891',SendTime:'2016-11-18 12:00:22',Consignee:'小店店长',ConsigneeTel:'18702111777',ConsigneeAddress:'玄武区苏宁大道1号预约1116002',OrderPartnerNo:'yg1010',AmountMoney:8888.12,Amount:1111,OrderDetails:[{MainCommodityName:'家佳康精装冰鲜肋排500g',Amount:8,Price:1111,AmountMoney:8888},{MainCommodityName:'家佳康精装冰鲜肋排800g',Amount:9,Price:111.11,AmountMoney:999.99}]}]");
}*/
function printOrders(ordersJSON) {
try {
var orders = eval(ordersJSON);
if (orders.length && orders.length > ) {
$("#container").html(dotFunc({orders: orders}));
$(".barcode").each(function (index, element) {
$(this).empty().barcode(orders[index].SerialNumber, barcodeType, barcodeSettings)
});
}
return orders.length > ;
} catch (e) {
return false;
}
}

参考文摘:

http://jinlong.github.io/doT/

http://olado.github.io/doT/index.html

http://www.mamicode.com/info-detail-874833.html

http://www.cnblogs.com/kuikui/p/3505768.html