template介绍
参考链接:tmpl基础介绍
轻量级模板引擎,零依赖,兼容服务器端环境;
使用方式:引入js文件 < script src = “ js / tmpl.min.js ” > </ script >
tmpl格式(渲染JSON): < script type = “ text / x-tmpl ” id = “ tmpl-demo ” > <h3>{%=o.title%}</h3><p>Released under the<a href="{%=o.license.url%}">{%=o.license.name%}</a>.</p><h4>Features</h4><ul>{%for(vari=0; i<o.features.length; i++) {%}<li>{%=o.features[i]%}</li>{%}%}</ul> </script>
其中:o指代的是js渲染时 json中的data,script类型需设为“text/x-tmpl”;
js(jquery)语法 :
vardata={"title":"JavaScript Templates","license":{"name":"MIT license","url":"https://opensource.org/licenses/MIT"},"features":["lightweight & fast","powerful","zero dependencies"]};
var dom = $('#dom');
dom.html(tmpl('tmpl-demo',data));
javascript: document.getElementById("dom").innerHTML=tmpl("tmpl-demo", data);
tmpl function
基于template基础用法的扩展,将tmpl作为function,渲染时通过传参将数据传递到tmpl模板中;
eg1: var tmplFun1 = tmpl('tmpl-demo1');
var dom1 = $('#dom1');
var data= {[{'id':1,'name':'name1'},{'id':2,'name':'name2'},{'id':3,'name':'name3'},{'id':4,'name':'name4'}]};
dom1.html(tmplFun1(data));
< script type = “ text / x-tmpl ” id = “ tmpl-demo1 ” >
<ul>
{%for(var i=0;i<o.length;i++) { %}
<li>{%=o[i].name%}</li>
{% } %}
</ul>
</script>
eg2:var tmplFun2 = tmpl('tmpl-demo2');
var dom2 = $('#dom2');
var data= {[{'id':1,'name':'name1'},{'id':2,'name':'name2'},{'id':3,'name':'name3'},{'id':4,'name':'name4'}]};
var strDom = " ";
data.forEach(function(val,index){
strDom + = tmplFun2(val);
});
dom1.html(strDom);
< script type = “ text / x-tmpl ” id = “ tmpl-demo1 ” >
<li>{%=o.name%}</li>
</script>
子模板
基于template扩展,tmpl中可拆分子模板,进行某些特殊处理
eg:
< script type = “ text / x-tmpl ” id = “ tmpl-demo1 ” >
{%if("条件") { %}
<li>{%=o.name%}</li>
{% } else { %}
{%include('tmpl-subTmpl',{id:o[i].id,name:o[i].name});%}
{% } %}
</script>
<script type = “ text / x-tmpl ” id = “ tmpl-subTmpl” >
<li>name:{%=o.name%}</li>
</script>
除了上面提到的if条件判断,for循环等 另外:template中还可使用变量传值,正则检测等;{%#o.content%} :将"=" 改为 "#"可原样输出内容;
网友评论