15

In my Handlebars template I check for the existence of a variable, and render some text if it's there:

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

This works fine if foo is text or if foo is numeric but not zero. But if

var foo = 0;

then {{#if foo}} returns false.

This appears to be yet another Javascript oddity, because Javascript itself behaves the same way. In Javascript code, though, you could get around this by checking if the variable is 'undefined'.

How can I do the same thing in Handlebars?

I could write an {{#exists}} helper, but I was hoping there was something built in.

4

4 回答 4

33

为此内置了一些东西:

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

这显示foo!whenfoo0

于 2014-06-22T17:17:36.827 回答
18

我会做得更好,并为 {{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}}
于 2013-08-28T02:33:21.917 回答
1

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

/**
 * The {{#exists}} helper checks if a variable is defined.
 */
Handlebars.registerHelper('exists', function(variable, options) {
    if (typeof variable !== 'undefined') {
        return options.fn(this);
    }
});
于 2013-06-13T20:23:52.593 回答
0

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

{{ /exist }}

并将其更改为:

{{/exist}}
于 2016-05-24T01:40:02.860 回答