doT.js
doT.js github地址
Created in search of the fastest and concise JavaScript templating function with emphasis on performance under V8 and nodejs. It shows great performance for both nodejs and browsers.
doT.js is fast, small and has no dependencies.
-
使用方法:
{{= }}
// for interpolation
{{ }}
//for evaluation
{{~ }}
//for array iteration
{{? }}
// for conditionals
{{! }}
// for interpolation with encoding
{{# }}
// for compile-time evaluation/includes and partials
{{## #}}
// for compile-time defines
-
調用方式:
var tmpText = doT.template(模板);
tmpText(數(shù)據(jù)源);
-
語法結構:
賦值:
//格式:
{{= }}
//示例:
<div id="show_list"></div>
<script id="tpl" type="text/x-dot-template">
<div>Hi {{=it.name}}!</div>
<div>{{=it.age || ''}}</div>
</script>
<script>
var data = {"name":"Jake","age":31};
var show_tpl = doT.template($("#tpl").text());
$("#show_list").html(show_tpl(data));
</script>
for 循環(huán)結構:
//格式:
{{ for(var x in data) { }}
{{= key }}
{{ } }}
//示例:
<div id="show_list"></div>
<script id="tpl" type="text/x-dot-template">
{{ for(var x in it) { }}
<div>KEY:{{= x }}---VALUE:{{= it[x] }}</div>
{{ } }}
</script>
<script>
var data = {
"name":"Jake",
"age":31,
"interests":["basketball","hockey","photography"],
"contact":{
"email":"jake@xyz.com",
"phone":"999999999"
}
};
var show_tpl = doT.template($("#tpl").text());
$("#show_list").html(show_tpl(data));
</script>
if 邏輯結構:
//格式:
{{if(conditions){ }}
{{} eles if(conditions){ }}
{{} eles{ }}
{{ }}}
//示例:
<div id="show_list"></div>
<script id="tpl" type="text/x-dot-template">
{{if(!it.name) { }}
<div>Oh, I love your name, {{=it.name}}!</div>
{{ } eles if(!it.age === 0) { }}
<div>Guess nobody named you yet!</div>
{{} eles{ }}
You are {{=it.age}} and still dont have a name?
{{ }}}
</script>
<script>
var data = {
"name":"Jake",
"age":31,
"interests":["basketball","hockey","photography"],
"contact":{
"email":"jake@xyz.com",
"phone":"999999999"
}
};
var show_tpl = doT.template($("#tpl").text());
$("#show_list").html(show_tpl(data));
</script>
數(shù)組:
//格式:
{{~data.array :value:index }}
//示例:
<div id="show_list"></div>
<script id="tpl" type="text/x-dot-template">
{{~it.array:value:index}}
<div>{{= index+1 }}{{= value }}!</div>
</script>
<script>
var data = {
"array":["banana","apple","orange"]
};
var show_tpl = doT.template($("#tpl").text());
$("#show_list").html(show_tpl(data));
</script>
編碼:
//格式:
{{!it.uri}}
//示例:
<div id="show_list"></div>
<script id="tpl" type="text/x-dot-template">
Visit {{!it.uri}} {{!it.html}}
</script>
<script>
var data = {
"uri":"http://bebedo.com/?keywords=Yoga",
"html":"<div style='background: #f00; height: 30px'>html元素</div>"
};
var show_tpl= doT.template($("#tpl").text());
$("#show_list").html(show_tpl(data));
</script>