Handlebars #if and numeric zeroes

匿名 (未验证) 提交于 2019-12-03 03:05:02

问题:

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}} 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!