在使用Handlebars模板時,由於在模板中if判斷很多時間無法滿足需求(if好像目前只支持對象爲否爲空),所以需要對if進行功能擴展,這裏需要用到handlebars的helper類庫,下面以兩個數比大小爲例來說明
1.定義比較大小的方法
//這裏需要引用Handlebars的運行時組件庫
let Handlebars = require("handlebars/runtime")["default"];
//註冊一個名字叫做compareTwoNum的方法,
Handlebars.registerHelper("compareTwoNum",function(v1,v2,options){
if(v1>v2){
//固定寫法,滿足if執行{{if}}部分
return options.fn(this);
}else{
//不滿足條件執行{{else}}部分
return options.inverse(this);
}
});
2.模板裏引用
<!--這裏以#開頭,然後接1中註冊的方法名,並以該方法名結束標籤-->
{{#compareTwoNum v1 v2}}
<!--滿足if需要執行的dom結構-->
{{else}}
<!--不滿足if需要執行的dom結構-->
{{/compareTwoNum}}
好了,就這麼簡單
Handlebars.js 更多教程:
1.http://www.cnblogs.com/iyangyuan/archive/2013/12/12/3471227.html
2.http://keenwon.com/992.html
3.http://www.ghostchina.com/introducing-the-handlebars-js-templating-engine/