Indranil Mondal
Indranil Mondal

Reputation: 2857

Check existence of a variable in handlebar

I've a javascript object like :

var data = {
"current" : 0,
"max" : 5,
"reward" : 5
};

And I'm crating a HTML with this data using handlebar like :

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

{{#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?

Upvotes: 19

Views: 39694

Answers (2)

Kiksot
Kiksot

Reputation: 9

instead of #if you should use #unless: https://handlebarsjs.com/guide/builtin-helpers.html#unless

Upvotes: 0

albertjan
albertjan

Reputation: 7817

This is by design if checks for falsy values see 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.

there's a includeZero option use like:

{{#if reward includeZero=true}}
{{/if}}

You can see the implementation of the helper here: on github

Upvotes: 36

Related Questions