Handlebars是一个模板
var tpl2='\
<ul class="list_top layoutfix">\
<li class="w_01">名称</li>\
<li class="w_02">原价</li>\
<li class="w_03">111</li>\
<li class="w_04">优惠</li>\
<li class="w_05">{{age}}</li>\
</ul>\
';
var html = Handlebars.compile(tpl2)({'age': 12});
document.body.innerHTML = html;
你可以自定义方法,让它变成和angular一样灵活
//相等
Handlebars.registerHelper('equal', function (a, b, v1, v2) {
return a == b ? v1 : v2;
});
//或者这样,它就像一个过滤器
Handlebars.registerHelper('regcheck', function (a) {
var reg = {
"1": "checkIdCard",
"2": "checkPassport",//护照
"10": "checkHKCard",//港澳通行证
"22": "checkTAIWAN",//台湾通行证
"6": "checkDriver"//驾驶证
};
return !!reg[a] ? reg[a] : "checkCard";
});
//还可以这样
// if增强 {{#ifPlus var1 '==' var2}}
Handlebars.registerHelper('ifPlus', function(v1, operator, v2, options) {
switch (operator) {
case '==':
return (v1 == v2) ? options.fn(this) : options.inverse(this);
case '===':
return (v1 === v2) ? options.fn(this) : options.inverse(this);
case '<':
return (v1 < v2) ? options.fn(this) : options.inverse(this);
case '<=':
return (v1 <= v2) ? options.fn(this) : options.inverse(this);
case '>':
return (v1 > v2) ? options.fn(this) : options.inverse(this);
case '>=':
return (v1 >= v2) ? options.fn(this) : options.inverse(this);
case '&&':
return (v1 && v2) ? options.fn(this) : options.inverse(this);
case '||':
return (v1 || v2) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
});
Handlebars.registerHelper('list', function(items, options) {
var out = "<ul>";
for(var i=0, l=items.length; i<l; i++) {
out = out + "<li>" + options.fn(items[i]) + "</li>";
}
return out + "</ul>";
});
//还能这样玩,仿佛是组件的雏形
var tpl3 = "{{#list people}}{{firstName}} {{lastName}}{{/list}}";
var data3 ={
people: [
{firstName: "Yehuda", lastName: "Katz"},
{firstName: "Carl", lastName: "Lerche"},
{firstName: "Alan", lastName: "Johnson"}
]
}
var html = Handlebars.compile(tpl3)(data3);
document.body.innerHTML= html;
有时候 需要传入一段html 我们可以使用{{{三个括号
更多可能等你探索
handlebarapi
handlebar官网