我有以下数据
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>
我正在尝试查看对象列表并根据类型属性呈现模板。这可能吗?
模板中的If else
效果不太好。
最佳答案
Handlebars 没有测试值的方法,但您可以使用像 Comparison block helper for handlebars templates 这样的帮助器测试 type
属性并呈现特定的 HTML block :
{{#compare type "radio"}}
Radio HTML
{{/compare}}
{{#compare type "checkbox"}}
Checkbox HTML
{{/compare}}
但是,您可能需要考虑转换数据。如果所有输入都是复选框或单选框,则可以对使用单选按钮的项目使用 bool 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 ...
});
关于javascript - Handlebars 根据值渲染模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14738468/