可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.
回答1:
I would go one better and provide a case for the {{else}} condition...
/** * 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); } });
Now you can have:
{{#exists myvar}} <p>Value of myvar is ... {{myvar}}</p> {{else}} <p>Please supply a myvar</p> {{/exists}}
回答2:
There is something built in for this:
{{#if foo includeZero=true}} foo! {{/if}}
This displays foo!
when foo
is 0
.
回答3:
I just went ahead and wrote an {{#exists}} helper. But if someone has a better solution, please post it.
/** * The {{#exists}} helper checks if a variable is defined. */ Handlebars.registerHelper('exists', function(variable, options) { if (typeof variable !== 'undefined') { return options.fn(this); } });
回答4:
If anyone gets this error "Expecting 'ID', 'DATA', got 'SEP'" using @Shane method make sure you have no spaces in:
{{ /exist }}
And change it to this:
{{/exist}}