doT模板引擎

doT是一个仅3kb的高性能模板引擎,以其简洁语法和无依赖特性受到青睐。本文介绍了如何进行插件代码使用、模板语法,包括调用方式、循环数组结构和选择结构。此外,展示了渲染模板的方法,如compile-time evaluation和interpolation with encoding。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

doT模板引擎是一个比较高效的引擎,一直都在使用,只有3kb大小,简洁的语法,无任何依赖,简单易用;下面的代码直接拷贝引用就可以使用;

插件代码

(function(){function p(b,a,d){return("string"===typeof a?a:a.toString()).replace(b.define||h,function(a,c,e,g){0===c.indexOf("def.")&&(c=c.substring(4));c in d||(":"===e?(b.defineParams&&g.replace(b.defineParams,function(a,b,l){d[c]={arg:b,text:l}}),c in d||(d[c]=g)):(new Function("def","def['"+c+"']="+g))(d));return""}).replace(b.use||h,function(a,c){b.useParams&&(c=c.replace(b.useParams,function(a,b,c,l){if(d[c]&&d[c].arg&&l){return a=(c+":"+l).replace(/'|\\/g,"_"),d.__exp=d.__exp||{},d.__exp[a]=d[c].text.replace(new RegExp("(^|[^\\w$])"+d[c].arg+"([^\\w$])","g"),"$1"+l+"$2"),b+"def.__exp['"+a+"']"}}));var e=(new Function("def","return "+c))(d);return e?p(b,e,d):e})}function k(b){return b.replace(/\\('|\\)/g,"$1").replace(/[\r\t\n]/g," ")}var f={version:"1.0.3",templateSettings:{evaluate:/\{\{([\s\S]+?(\}?)+)\}\}/g,interpolate:/\{\{=([\s\S]+?)\}\}/g,encode:/\{\{!([\s\S]+?)\}\}/g,use:/\{\{#([\s\S]+?)\}\}/g,useParams:/(^|[^\w$])def(?:\.|\[[\'\"])([\w$\.]+)(?:[\'\"]\])?\s*\:\s*([\w$\.]+|\"[^\"]+\"|\'[^\']+\'|\{[^\}]+\})/g,define:/\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,defineParams:/^\s*([\w$]+):([\s\S]+)/,conditional:/\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,iterate:/\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,varname:"it",strip:!0,append:!0,selfcontained:!1,doNotSkipEncoded:!1},template:void 0,compile:void 0},m;f.encodeHTMLSource=function(b){var a={"&":"&#38;","<":"&#60;",">":"&#62;",'"':"&#34;","'":"&#39;","/":"&#47;"},d=b?/[&<>"'\/]/g:/&(?!#?\w+;)|<|>|"|'|\//g;return function(b){return b?b.toString().replace(d,function(b){return a[b]||b}):""}};m=function(){return this||(0,eval)("this")}();"undefined"!==typeof module&&module.exports?module.exports=f:"function"===typeof define&&define.amd?define(function(){return f}):m.doT=f;var r={start:"'+(",end:")+'",startencode:"'+encodeHTML("},s={start:"';out+=(",end:");out+='",startencode:"';out+=encodeHTML("},h=/$^/;f.template=function(b,a,d){a=a||f.templateSettings;var n=a.append?r:s,c,e=0,g;b=a.use||a.define?p(a,b,d||{}):b;b=("var out='"+(a.strip?b.replace(/(^|\r|\n)\t* +| +\t*(\r|\n|$)/g," ").replace(/\r|\n|\t|\/\*[\s\S]*?\*\//g,""):b).replace(/'|\\/g,"\\$&").replace(a.interpolate||h,function(b,a){return n.start+k(a)+n.end}).replace(a.encode||h,function(b,a){c=!0;return n.startencode+k(a)+n.end}).replace(a.conditional||h,function(b,a,c){return a?c?"';}else if("+k(c)+"){out+='":"';}else{out+='":c?"';if("+k(c)+"){out+='":"';}out+='"}).replace(a.iterate||h,function(b,a,c,d){if(!a){return"';} } out+='"}e+=1;g=d||"i"+e;a=k(a);return"';var arr"+e+"="+a+";if(arr"+e+"){var "+c+","+g+"=-1,l"+e+"=arr"+e+".length-1;while("+g+"<l"+e+"){"+c+"=arr"+e+"["+g+"+=1];out+='"}).replace(a.evaluate||h,function(a,b){return"';"+k(b)+"out+='"})+"';return out;").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\r/g,"\\r").replace(/(\s|;|\}|^|\{)out\+='';/g,"$1").replace(/\+''/g,"");c&&(a.selfcontained||!m||m._encodeHTML||(m._encodeHTML=f.encodeHTMLSource(a.doNotSkipEncoded)),b="var encodeHTML = typeof _encodeHTML !== 'undefined' ? _encodeHTML : ("+f.encodeHTMLSource.toString()+"("+(a.doNotSkipEncoded||"")+"));"+b);try{return new Function(a.varname,b)}catch(q){throw"undefined"!==typeof console&&console.log("Could not create a template function: "+b),q}};f.compile=function(b,a){return f.template(b,null,a)}})();

模板语法

所有的js语句都要写在{{}}

要渲染的数据变量要写在{{=变量名}}

调用方式

var temText = doT.template(模版);
// 模版是指script的标签内的内容, 直接使用选择器选择script标签即可
temText = (数据源)
// 你要渲染的数据源

我经常用的一个方法就是

HTML

<div id="temp"></div>
<script type="text/x-dot-template" id="listT">
    {{ for (var i = 0; i < it.length; i++) { }} 
        <p>{{=it[i].name}}</p>
    {{ }; }}
</script>

JS

// doT模版获取数据
function getData(data) {
    var listTText = document.getElementById('listT').text;
    var fnListT = doT.template(listTText);
    var html = fnListT(data);
    var list = document.getElementById('temp');
    list.innerHTML = html
}

循环数组结构

{{~it:value:index}}
    <p>{{=index}}-{{=value.name}} </p>
{{~}}
<!-- it是要遍历的数组, `:value`是数组的值, `:index`是数组索引, 顺序不能颠倒, 第一个是值,第二个是索引 -->

选择结构

{{?}} if
{{?? }} else if
{{??}} else
{{?}} 最后的 }

渲染模板

模板要写在script标签中

<script type="text/x-dot-template" id="listT">
    // 模板代码 
</script>

以上是工作中经常会用到的;还有一些功能我一次都没有用到过

for compile-time evaluation/includes and partials

{{## #}} for compile-time defines

数据源:{"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));

for interpolation with encoding

数据源:{"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));

欢迎访问我的博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值