javascript 检查车把中是否存在变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24352151/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check existence of a variable in handlebar
提问by Indranil Mondal
I've a javascript object like :
我有一个 javascript 对象,如:
var data = {
"current" : 0,
"max" : 5,
"reward" : 5
};
And I'm crating a HTML with this data using handlebar like :
我正在使用像这样的车把用这些数据创建一个 HTML:
<div>
<span>Current : {{current}}</span>
<span>Max : {{max}}</span>
<span>Reward: {{reward}}</span>
</div>
Now the problem is, the reward property may not be always present in the data, and in that case I don't want to show that span. So, I made the following:-
现在的问题是,reward 属性可能并不总是存在于数据中,在这种情况下,我不想显示该跨度。所以,我做了以下事情:-
{{#if reward}}
<span>Reward: {{reward}}</span>
{{/if}}
And it's working, if the reward property is not present, it's not showing the span, but it's also not showing the span if the value of reward is 0, can anybody suggest how to solve it. I can use some helper function. But, can I do that without using any helper function?
并且它正在工作,如果奖励属性不存在,则不会显示跨度,但是如果奖励的值为 0,它也不会显示跨度,任何人都可以建议如何解决它。我可以使用一些辅助功能。但是,我可以在不使用任何辅助函数的情况下做到这一点吗?
回答by albertjan
This is by design if
checks for falsy
values see handlebarsjs.com
这是通过设计if
检查falsy
值,请参阅handlebarsjs.com
You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "" or [] (a "falsy" value), Handlebars will not render the block.
您可以使用 if 帮助器有条件地渲染块。如果其参数返回 false、undefined、null、"" 或 [](“falsy”值),则 Handlebars 将不会渲染该块。
there's a includeZero
option use like:
有一个includeZero
选项使用,如:
{{#if reward includeZero=true}}
{{/if}}
You can see the implementation of the helper here: on github
您可以在此处查看 helper 的实现:在 github 上