Reputation: 39
I am trying to use if condition in embers js. But value not passing properly.
If Condition
{{#each item.model }}
{{#ifCond item.title Raja}}
<div>equal to</div>
{{else}}
<div>not equal to</div>
{{/ifCond}}
{{/each}}
This my HandleBar
Handlebars.registerHelper('ifCond', function (v1, v2, options) {
alert(v1);
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
my problem is alert showing value item.title
But I want value sample.
Here my Json
posts = [{
title: "sample",
body: "There are lots of à la carte software environments in this world."
}, {
title: "Broken Promises",
body: "James Coglan wrote a lengthy article about Promises in node.js."
}];
Upvotes: 1
Views: 448
Reputation: 140234
If you are using handlebars version 2 you can just create operators and use the core if helper
Handlebars.registerHelper('eq', function (lhs, rhs) {
return lhs == rhs;
});
Usage:
{{#if (eq title "Raja")}}
<div>equal to</div>
{{else}}
<div>not equal to</div>
{{/if}}
Upvotes: 0
Reputation: 11671
It is possible to evaluate values using the current context within the helper.
Example,
http://emberjs.jsbin.com/dixokezafe/1/edit?html,js
hbs
<script type="text/x-handlebars" data-template-name="index">
{{#each model }}
{{#ifCond title Raja}}
<div>equal to</div>
{{else}}
<div>not equal to</div>
{{/ifCond}}
{{/each}}
<button {{action "addObject"}}> add random object</button>
js
App.IndexRoute = Ember.Route.extend({
model: function() {
return posts;
}
});
App.IndexController = Em.ArrayController.extend({
actions:{
addObject:function(){
this.get("model").pushObject({
title: Math.floor(Math.random()*2)===0?"Raja":"something else",
body: "James Coglan wrote a lengthy article about Promises in node.js."
});
}
}
});
var posts = [{
title: "sample",
body: "There are lots of à la carte software environments in this world."
}, {
title: "Broken Promises",
body: "James Coglan wrote a lengthy article about Promises in node.js."
},
{
title: "Raja",
body: "James Coglan wrote a lengthy article about Promises in node.js."
}];
Handlebars.registerHelper('ifCond', function (v1, v2, options) {
var _v1 = Em.get(this,v1);
var _v2 = Em.get(this,v2);
v1 = Em.isEmpty(_v1)?v1:_v1;
v2 = Em.isEmpty(_v2)?v2:_v2;
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
});
It seems that it is not possible to register a bound helper and use it in block form. Checkout some links with interesting approaches tackling this issue.
http://discuss.emberjs.com/t/a-way-to-let-users-define-custom-made-bound-if-statements/2583
https://gist.github.com/slindberg/9924116
http://paarsgames.nl/2014/02/02/creating-your-own-custom-handlebars-bounded-ifs-in-ember/
Upvotes: 1