简体   繁体   中英

Failed to pass value to handlebars helper

I want to compare two values in template hence i have used handlebars helper as given below :

Handlebars.registerHelper('ifCond', function(v1, v2, options) {
    console.log(v1);console.log(v2);
  if(v1 === v2) {
    return options.fn(this);
  }
  return options.inverse(this);
});

My template code :

{{#ifCond item.id 1}}                           
    <div class="row" style="margin-top:0px;">                           
{{else}}
    <div class="row" style="margin-top:5px;">
{{/ifCond}} 

But value of item.id is not getting pass to helper it showing its value as "item.id".

Can anyone tell me what is the mistake in my above code?

I would not recommend altering between markup with an if statement. I have done it myself and this is a brittle approach and not very concise. I would always try to use the helper {{bind-attr}} (the helper is called {{bindAttr}} in rc7 and below).

CSS:

row.margin-top{
  margin-top: 5px;
}

Template:

<div class="row" {{bindAttr class="item.isWithMargin:margin-top"}}>

This is not the most elegant approach, as you would have css specific logic in your model. There fore you could iterate over your items and assign an itemController to each item and place the logic in this controller.

{{#each item in controller itemController="yourItemController"}}
<!-- this would resolve to App.YourItemController -->
App.YourItemController = Ember.ObjectController({
  isWithMargin : function(){
    return this.get("model.id") == 1;
  }.property("model.id")
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM