简体   繁体   English

把手:有条件地添加属性

[英]handlebars: conditionally add attribute

I'm trying to render a select element with options, like this 我正在尝试使用选项渲染一个select元素,就像这样

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

I'm using the following handlebars helper 我正在使用以下车把助手

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

The problem is that the selected attribute doesn't show up on any of the option element, but when I place a console.log in the handlebar helper I do see that one matches (input === color === true). 问题是selected属性没有出现在任何option元素上,但是当我在把手助手中放置一个console.log ,我确实看到一个匹配(输入=== color === true)。 Any ideas what I do wrong here ? 我在这里做错了什么想法?

This is a working example of what is described, 这是所描述内容的一个工作示例,

http://jsfiddle.net/rtLGR/ http://jsfiddle.net/rtLGR/

hbs 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 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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