Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 670
Indranil Mondal Avatar asked Jun 22 '14 14:06

Indranil Mondal


People also ask

What are Handlebars lookup?

lookup. The lookup helper allows for dynamic parameter resolution using Handlebars variables. This is useful for resolving values for array indexes. template {{#each people}} {{.

How do you compare handlebar values?

{{if}} is used to check whether a field has a value or not, whereas {{compare}} is used to check whether a field has one value or another value. Check out our Handlebars helper reference for more information on handlebars {{compare}}, {{if}}, and other handlebars expressions!

How do you iterate objects in Handlebars?

To iterate over an object with JavaScript and Handlebars. js, we can use the #each keyword. to add the Handlebars script and the template for looping through each entry in data . We use #each this to loop through each array property.


1 Answers

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

like image 109
albertjan Avatar answered Sep 23 '22 14:09

albertjan