javascript - Handlebars 根据值渲染模板

标签 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>

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

模板中的

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/

相关文章:

javascript - 在工具提示模板 kendo UI 中一起显示系列和 y 轴数据的值

javascript - 如何使用 JavaScript 打印网页上的非常大的图像

javascript - Backbone.js vs Express vs Next JS ...和JSP?

javascript - Mootools 类 - 在类属性中存储对文档正文的引用

javascript - 使用 Gulp 基于 Handlebars 模板编译 partials 和 markdown

javascript - 通过 ViewerJS 获取 PDF 中的页数

javascript - 如何在 kendo ui 中拖放面板栏?

javascript - 为什么 Bootstrap 需要 jQuery?

PHP 还是 JS 模板引擎? (对于同一 html 的多个 block )

javascript - 在 Handlebars 模板内执行 javascript