前沿
在日常开发中,前端要动态渲染数据时,如果用for去循环插入数据,会显得js很杂乱。
因此,我建议引入模板引擎。本文demo采用Handlebars
简介
Handlebars 是 JavaScript 一个语义模板库,通过对view和data的分离来快速构建Web模板。
基础用法
需要先引入handlebars.js transFormatJson.js
transFormatJson 可以自定义过滤器,将数据作为参数,传给Helper,然后在Helper中return过滤后的结果
@index可以返回当前数据的索引
html
<div id="content"></div>
<script id="tpl" type="text/x-handlebars-template">
{{#each this}}
{{#if title}}
<div>{{changeTitle title @index}}</div>
{{else}}
<div>这条数据没有title</div>
{{/if}}
{{/each}}
</script>
javascript
var list = [{title: "测试标题"}, {title: "测试标题"}, {}];
$("#content").html(Handlebars.compile($("#tpl").html())(list));
transFormatJson.js
Handlebars.registerHelper("changeTitle", function (title, index) {
return title + index;
// 如果要返回dom,则:return new Handlebars.SafeString("<div>...</div>");
});