I have the follow data
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"]},
]
Here are the templates
<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>
I’m trying to go down the list of objects and render the template based on the type attribute. Is this possible?
If else within the template didn’t work out too well.
Handlebars doesn’t have a way of testing values, but you could use a helper like Comparison block helper for handlebars templates to test the
typeproperty and render a particular block of HTML:However, you might want to consider transforming your data. If all inputs are either checkboxes or radios, perhaps use a boolean
radioproperty for items that use the radio buttons. Your data would now look like:Then you can use if/else:
Or, just do the template selection in the calling code: