【问题标题】:Handlerbars.js using an helper function in a #if statementHandlebars.js 在#if 语句中使用辅助函数
【发布时间】:2011-12-18 20:19:50
【问题描述】:

对于handlebars.js,我想根据生成的 json 显示两个 html 块。

假设我想感谢我的用户在我的商店订购商品。 我这样写我的 handlerbars.js 模板:

<p>{{name}}</p>
{{#if costIsZero}}
  Can't find any order
{{else}}
    You bought {{cost}} items in our shop, thanks.
{{/if}}

我正在为 costIsZero 编写一个简单的助手,如下所示:

Handlebars.registerHelper('costIsZero', function(){
    return this.cost == 0
});

当我将它与以下 json 数据混合时:

var data = {
  "name":"foo",
  "cost": 9
};

无论“成本”的值是多少,{{#if costIsZero}} 似乎总是正确的。 如果我注释掉助手本身,因此对于 costIsZero 没有任何内容,它总是返回 false。

以上所有代码都可以作为 JSFiddle 使用 http://jsfiddle.net/gsSyt/

我做错了什么?

也许我在劫持 handlebars.js 的工作方式,但在这种情况下,我应该如何使用 handlebars.js 实现我的功能?

【问题讨论】:

    标签: javascript templating mustache


    【解决方案1】:

    在评估 costIsZero 等表达式时不会调用帮助程序。

    您可以创建一个自定义助手来替代if

    Handlebars.registerHelper('ifCostIsZero', function(block) {
        if (this.cost == 0) {
            return block(this);
        } else {
            return block.inverse(this);
        }
    });
    

    你会这样使用:

    {{#ifCostIsZero}}
        Can't find any order
    {{else}}
        You bought {{cost}} items in our shop, thanks.
    {{/ifCostIsZero}}
    

    或者,您可以使用股票if(或unless),因为您的测试是针对零的:

    {{#if cost}}
        You bought {{cost}} items in our shop, thanks.
    {{else}}
        Can't find any order
    {{/if}}
    

    你可以在http://jsfiddle.net/gsSyt/41/玩这两个选项

    【讨论】:

    • 只是一个小评论。 block(this) 不再有效。你必须使用 block.fn(this);
    【解决方案2】:

    试试这个:

    Handlebars.registerHelper('if', function(conditional, block) {
      if(this.cost == 0) {
        return block(this);
      } else {
        return block.inverse(this);
      }
    })
    

    http://jsfiddle.net/mZbtk/2/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-29
      • 2012-02-26
      • 2019-01-17
      • 2019-09-20
      相关资源
      最近更新 更多