2014-04-01 127 views
9

我試圖渲染選項中選擇元素,像這樣車把:有條件地添加屬性

<select dropdown multiple class="dropdown" name="color"> 
     {{#each colors}} 
      <option value="{{value}}" {{isSelected parentColor id}}>{{title}}></option> 
     {{/each}} 
</select> 

我用下面的把手幫手

Handlebars.registerHelper('isSelected', function(input, color) { 
    return input === color ? 'selected' : ''; 
}); 

的問題是,selected屬性不會顯示在任何option元素上,但是當我將console.log放置在手柄助手中時,我確實看到一個匹配(輸入===顏色===真)。任何想法我在這裏做錯了嗎?

回答

10

這就是所描述的工作示例,

http://jsfiddle.net/rtLGR/

HBS

<h1>Handlebars JS Example</h1> 
<script id="some-template" type="text/x-handlebars-template"> 

    <select dropdown multiple class="dropdown" name="color"> 
     {{#each colors}} 
      <option value="{{value}}" {{isSelected parentColor id}}>{{title}}</option> 
     {{/each}} 
</select> 
</script> 

JS

var source = $("#some-template").html(); 
var template = Handlebars.compile(source); 

var data = { 
    colors: [ 
     {id:1,value:1,title:"red",parentColor:2}, 
     {id:2,value:2,title:"green",parentColor:2}, 
     {id:3,value:3,title:"blue",parentColor:1} 
    ] 
}; 


Handlebars.registerHelper('isSelected', function (input, color) { 
    return input === color ? 'selected' : ''; 
}); 

$('body').append(template(data));