在使用mustache.js時候, 遇到一些格式化時間這樣的功能, 總會很麻煩.
好比:javascript
{ "items":[ { "title" : "標題1", "createDate":"2016-06-10T15:48:00.000Z" }, { "title" : "標題2", "createDate":"2016-06-10T18:48:00.000Z" } ] }
要想格式化列表裏的時間createDate, 你必需要在數據對象中像這樣註冊一個handler:html
{ items : ... dateFromat : function(){ return moment(this.createDate).format('YYYY-MM-DD') } }
每次作渲染的時候都必須重複註冊handler,非常麻煩.
註冊完後,使用handler的時候語法也很奇葩:前端
{{#items}} <h3 class="list-group-item-heading">{{title}}</h3> {{#dateFromat}} <span>{{formatDate createDate}}</span> {{/dateFromat}} {{/items}}
爲此, 特地google了一下. 發現了另外一個語法兼容mustache的前段模板Handlerbar, 和它的名字表達的同樣, 能夠方便的註冊一堆handler.java
使用方式很簡單:git
註冊handlergithub
Handlebars.registerHelper('formatDate', function(date) { return moment(date).format('YYYY-MM-DD hh:mm:ss'); });
渲染時調用handlerjson
{{#items}} <h3 class="list-group-item-heading">{{title}}</h3> <span>{{formatDate createDate}}</span> {{/items}}
ok.this
另外,它提供的Html預編譯成JavaScript功能也很方便. google
不愧是大型前端工程的利器.spa