JS模板引擎像百度的baiduTemplate(百度)\artTemplate(騰訊)\juicer(淘寶)\doT\ tmpl\ handlebars\ easyTemplate\ underscoretemplate \ mustache \kissytemplatejavascript
doT.js 靈感來源於搜尋基於 V8 和 Node.js ,強調性能,最快速最簡潔的 JavaScript 模板函數html
引入 javascript 文件:java
<script type="text/javascript" src="doT.js"></script>
jquery
doT.templateSettings - 默認編譯設置ios
能夠經過改變編譯設置自定義 doT。這是默認設置:git
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 中的正則表達式。github
這是默認的定界符列表:正則表達式
{{ }} 用於求值(evaluation) {{= }} 用於插值(interpolation) {{! }} 用於編碼求值(interpolation with encoding) {{# }} 用於編譯時求值/引入和局部模板(compile-time evaluation/includes and partials) {{## #}} 用於編譯時定義(compile-time defines) {{? }} 條件語句(conditionals) {{~ }} 數組迭代(array iteration)
調用方式:
var tmpText = doT.template(模板);
tmpText(數據源);json
用法示例:數組
for 循環前判斷循環的list是否爲空
<script id="invoiceListDot" type="text/x-dot-template"> {{? it.invoiceInfoDtos}} {{ for(var prop=0;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": "1", "name": "衣服", "goods": [ { "goods_id": "1", "name": "衣服1", "price": "100", "logoimg": "http://image.diandodo.com/zhudianbao/Uploads/User/u1250000222/20160723/201607231342158687.png@250h_250w_1e_1c" }, { "goods_id": "2", "name": "衣服2", "price": "200", "logoimg": "http://image.diandodo.com/zhudianbao/Uploads/User/u1250000222/20160723/201607231342158687.png@250h_250w_1e_1c" } ] }, { "id": "2", "name": "鞋子", "goods": [ { "goods_id": "3", "name": "鞋子1", "price": "100", "logoimg": "http://image.diandodo.com/zhudianbao/Uploads/User/u1250000222/20160723/201607231342158687.png@250h_250w_1e_1c" }, { "goods_id": "4", "name": "鞋子2", "price": "200", "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=0, 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=0, 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==1 }}K{{?? it.productPrice.policyInfo.storageUnit==2}}M{{?? it.productPrice.policyInfo.storageUnit==3}}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==1 }} 年{{?? it.productPrice.policyInfoDto.periodUnit==2}}月{{?? it.productPrice.policyInfoDto.periodUnit==3}}天 {{?? }}單位未知 {{? }} <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":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));
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));
循環數組{{~}}
格式: {{~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));
條件渲染{{?}}{{??}},至關於原生的if else if
格式: {{? }} 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 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":31} 區域:<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":31,"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 > 0) { $("#container").html(dotFunc({orders: orders})); $(".barcode").each(function (index, element) { $(this).empty().barcode(orders[index].SerialNumber, barcodeType, barcodeSettings) }); } return orders.length > 0; } 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