Handlebars.js if 功能扩展

来源:互联网 发布:海关数据免费查询系统 编辑:程序博客网 时间:2024/06/06 13:59

在使用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/

原创粉丝点击