1

我有以下数据

multipleTypes = [
        {"type": "radio", "label": "Cool people names","option": ["Ralgar", "Mozzy"]},
        {"type": "checkbox", "label": "Cool phones", "option": ["android", "iphone"]}
        {"type": "radio", "label": "Cool pets", "option": ["monster", "moose"]},
        {"type": "checkbox", "label": "Cool places", "option": ["bar", "undercovers", "moon"]},
    ]

这里是模板

<script id="checkbox-template" type="text/x-handlebars-template">
    <fieldset>
        <legend>{{label}}</legend>
        {{#each option}}
            <label for="regularCheckbox">
                <input type="checkbox" id="regularCheckbox" value="checkbox 1">
                <span>{{this}}</span>
            </label>
        {{/each}}
    </fieldset>
</script>
<script id="radio-template" type="text/x-handlebars-template">
    <fieldset>
        <legend>{{label}}</legend>
        {{#each option}}
            <label for="regularRadio">
                <input type="radio" name="radios" id="regularRadio" value="radio 1">
                <span>{{this}}</span>
            </label>
        {{/each}}
    </fieldset>
</script>

我正在尝试查看对象列表并根据 type 属性呈现模板。这可能吗?

If else模板内的效果不太好。

4

2 回答 2

0

这个怎么样?

Handlebars.registerHelper('typeRadio', function(obj) {
    return obj.type === 'radio';
});
Handlebars.registerHelper('typeCheckbox', function(obj) {
    return obj.type === 'checkbox';
});

然后在您的模板中,使用:

<fieldset>
    <legend>{{label}}</legend>
    {{#if typeRadio}}
        // do radio stuff
    {{/if}}
    {{#if typeCheckbox}}
        // do checkbox stuff
    {{/if}}

</fieldset>
于 2013-02-06T21:00:11.227 回答
0

Handlebars 没有测试值的方法,但是您可以使用像Comparison block helper 这样的 helper来测试车把模板type的属性并呈现特定的 HTML 块:

{{#compare type "radio"}}
Radio HTML
{{/compare}}
{{#compare type "checkbox"}}
Checkbox HTML
{{/compare}}

但是,您可能需要考虑转换数据。如果所有输入都是复选框或单选,则可能radio对使用单选按钮的项目使用布尔属性。您的数据现在看起来像:

multipleTypes = [
    {"radio": true, "label": "Cool people names","option": ["Ralgar", "Mozzy"]},
    {"radio": false, "label": "Cool phones", "option": ["android", "iphone"]}
    {"radio": true, "label": "Cool pets", "option": ["monster", "moose"]},
    {"radio": false, "label": "Cool places", "option": ["bar", "undercovers", "moon"]},
]

然后你可以使用 if/else:

{{#if radio}}
Radio HTML
{{else}}
Checkbox HTML
{{/if}}

或者,只需在调用代码中进行模板选择:

var templates = {
  'radio': Handlebars.compile($('#radio-template').html()),
  'checkbox': Handlebars.compile($('checkbox-template').html())
};
multipleTypes.forEach(function(item) {
  var rendered = templates[item.type](item);
  // Do something with rendered output ...
});
于 2013-02-06T21:02:04.203 回答