With handlebars.js I want to display two blocks of html depending of a resulting json.
Let's say I want to thanks my user for ordering items at my shop. I write my handlerbars.js template like this :
<p>{{name}}</p>
{{#if costIsZero}}
Can't find any order
{{else}}
You bought {{cost}} items in our shop, thanks.
{{/if}}
I'm coding a simple helper for costIsZero like this :
Handlebars.registerHelper('costIsZero', function(){
return this.cost == 0
});
When I mix it with the following json data :
var data = {
"name":"foo",
"cost": 9
};
Whatever the value of "cost" is the {{#if costIsZero}} seems always to be true. If I ment out the helper itself, thus having nothing for costIsZero it returns always false.
All the code above is available as a JSFiddle there /
What I'm doing wrong ?
Maybe I'm hijacking the way handlebars.js work, but in that case, How should I implement my feature with handlebars.js ?
With handlebars.js I want to display two blocks of html depending of a resulting json.
Let's say I want to thanks my user for ordering items at my shop. I write my handlerbars.js template like this :
<p>{{name}}</p>
{{#if costIsZero}}
Can't find any order
{{else}}
You bought {{cost}} items in our shop, thanks.
{{/if}}
I'm coding a simple helper for costIsZero like this :
Handlebars.registerHelper('costIsZero', function(){
return this.cost == 0
});
When I mix it with the following json data :
var data = {
"name":"foo",
"cost": 9
};
Whatever the value of "cost" is the {{#if costIsZero}} seems always to be true. If I ment out the helper itself, thus having nothing for costIsZero it returns always false.
All the code above is available as a JSFiddle there http://jsfiddle/gsSyt/
What I'm doing wrong ?
Maybe I'm hijacking the way handlebars.js work, but in that case, How should I implement my feature with handlebars.js ?
Share Improve this question edited Dec 18, 2011 at 20:25 JeanLaurent asked Dec 18, 2011 at 20:19 JeanLaurentJeanLaurent 7142 gold badges8 silver badges12 bronze badges2 Answers
Reset to default 5Helpers are not invoked when evaluating an expression such as costIsZero
.
You could create a custom helper that works as an alternative to if
:
Handlebars.registerHelper('ifCostIsZero', function(block) {
if (this.cost == 0) {
return block(this);
} else {
return block.inverse(this);
}
});
Which you would use like this:
{{#ifCostIsZero}}
Can't find any order
{{else}}
You bought {{cost}} items in our shop, thanks.
{{/ifCostIsZero}}
Alternatively, you can use the stock if
(or unless
) since your test is against zero :
{{#if cost}}
You bought {{cost}} items in our shop, thanks.
{{else}}
Can't find any order
{{/if}}
You can play with both options at http://jsfiddle/gsSyt/41/
Try this:
Handlebars.registerHelper('if', function(conditional, block) {
if(this.cost == 0) {
return block(this);
} else {
return block.inverse(this);
}
})
http://jsfiddle/mZbtk/2/