Handlebars.js的Helper实现比较大小、或的功能

//注册一个比较大小的Helper
Handlebars.registerHelper("compare",function(v1,v2,options){
    if(v1>v2){
        return options.fn(this);    //满足条件执行,返回 this数据
    }else{
        return options.inverse(this);//不满足条件执行,不返回 this数据
    }
})
//注册一个 条件为或的块
Handlebars.registerHelper("orConditon",function(a,b,options){
    if(a||b){
        return options.fn(this);
    }else{
        return options.inverse(this)
    }
})
//例子
<script id="table-template" type="text/x-handlebars-template">
    {{#each student}}
    {{#if name}}
    {{#compare age 20}}
    <tr>
        <td>{{name}}</td>
        <td>{{sex}}</td>
        <td>{{age}}</td>
        <td>{{num}}</td>
        <td>{{max}}</td>
    </tr>
    {{else}}
    <tr>
        <td>?</td>
        <td>?</td>
        <td>?</td>
    </tr>
    {{/compare}}
    {{#orConditon num max}}
    <tr>
        <td>{{name}}</td>
        <td>{{sex}}</td>
        <td>{{age}}</td>
        <td>{{num}}</td>
        <td>{{max}}</td>
    </tr>
    {{/orConditon}}
    {{/if}}
    {{/each}}
</script>

<!--进行数据处理、html构造-->
<script type="text/javascript">
  $(document).ready(function() {
    //模拟的json对象
    var data = {
      "student": [
        {
          "name": "张三",
          "sex": "0",
          "age": 23,
          "num": true,
          "max": 3
        },
        {
          "sex": "0",
          "age": 22,
          "num": '3',
          "max":true

        },
        {
          "name": "妞妞",
          "sex": "1",
          "age": 18,
          "max":'3'
        }
      ]
    };    
    //注册一个比较大小的Helper,判断v1是否大于v2
    Handlebars.registerHelper("compare",function(v1,v2,options){
      if(v1>v2){
        //满足添加继续执行
        return options.fn(this);
      }else{
        //不满足条件执行{{else}}部分
        return options.inverse(this);
      }
    });
    //注册一个 条件为或的块
    //option是所有的数据对象, fn就是执行什么, inverse就是不执行
    Handlebars.registerHelper("orConditon",function(a,b,options){
      if(a||b){
        return options.fn(this);
      }else{
        return options.inverse(this)
      }
    })

   
  });
</script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值