【问题标题】:Handlebars #if and numeric zeroes车把 #if 和数字零
【发布时间】:2016-05-24 10:09:16
【问题描述】:

在我的 Handlebars 模板中,我检查变量是否存在,如果存在则渲染一些文本:

{{#if foo}}
  some text
{{/if}}

如果 foo 是文本或 foo 是数字但不为零,这很好用。但是如果

var foo = 0;

然后{{#if foo}} 返回 false。

这似乎是另一个 Javascript 怪异,因为 Javascript 本身的行为方式相同。但是,在 Javascript 代码中,您可以通过检查变量是否为“未定义”来解决此问题。

如何在 Handlebars 中做同样的事情?

我可以写一个 {{#exists}} 助手,但我希望有一些内置的东西。

【问题讨论】:

    标签: handlebars.js


    【解决方案1】:

    为此内置了一些东西:

    {{#if foo includeZero=true}}
        foo!
    {{/if}}
    

    foo0 时,这将显示foo!

    【讨论】:

    【解决方案2】:

    我会做得更好,并为 {{else}} 条件提供一个案例...

    /**
     * The {{#exists}} helper checks if a variable is defined.
     */
    Handlebars.registerHelper('exists', function(variable, options) {
        if (typeof variable !== 'undefined') {
            return options.fn(this);
        } else {
            return options.inverse(this);
        }
    });
    

    现在你可以拥有:

    {{#exists myvar}}
      <p>Value of myvar is ... {{myvar}}</p>
    {{else}}
      <p>Please supply a myvar</p>
    {{/exists}}
    

    【讨论】:

      【解决方案3】:

      我只是继续写了一个 {{#exists}} 助手。但如果有人有更好的解决方案,请发布。

      /**
       * The {{#exists}} helper checks if a variable is defined.
       */
      Handlebars.registerHelper('exists', function(variable, options) {
          if (typeof variable !== 'undefined') {
              return options.fn(this);
          }
      });
      

      【讨论】:

        【解决方案4】:

        如果有人使用@Shane 方法收到此错误“期望'ID','DATA',得到'SEP'”,请确保您没有空格:

        {{ /exist }}
        

        把它改成这样:

        {{/exist}}
        

        【讨论】:

          猜你喜欢
          • 2012-07-08
          • 2016-06-18
          • 1970-01-01
          • 1970-01-01
          • 2016-07-31
          • 1970-01-01
          • 2017-05-06
          • 2014-08-17
          • 1970-01-01
          相关资源
          最近更新 更多