把手根据价值渲染模板

时间:2013-02-06 20:47:03

标签: javascript javascript-framework handlebars.js

我有以下数据

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效果不佳。

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

Handlebars没有办法测试值,但您可以使用Comparison block helper for handlebars templates之类的帮助程序来测试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 ...
});
相关问题