I have the following data that I am trying to feed into a Handlebar template
{
"set-group": [
{
"label": "Source Data",
"type": "select",
"options": [
{
"value": "Default Selections"
},
{
"value": "Other Selections"
}
]
},
{
"label": "Scale",
"type": "radio",
"options": [
{
"value": "log",
"label": "Log",
"groupname": "group2"
},
{
"value": "linear",
"label": "Linear",
"groupname": "group2"
}
]
}
]
}
I created and registered 2 Partials, one that templates "selects" form elements and one that templates "radio" inputs. I cannot know what type of form element will be in the data so I need some sort of helper that checks if type == select and applies the appropriate partial for the select. I am having trouble with creating such a helper.
I was thinking of replacing type=select in the data to just select=true and just check for true/false using the if/else helper but I would rather keep the format standardized
Any ideas?
I ended up using this helper
// Comparison Helper for handlebars.js
// Pass in two values that you want and specify what the operator should be
// e.g. {{#compare val1 val2 operator="=="}}{{/compare}}
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
operator = options.hash.operator || "==";
var operators = {
'==': function(l,r) { return l == r; },
'===': function(l,r) { return l === r; },
'!=': function(l,r) { return l != r; },
'<': function(l,r) { return l < r; },
'>': function(l,r) { return l > r; },
'<=': function(l,r) { return l <= r; },
'>=': function(l,r) { return l >= r; },
'typeof': function(l,r) { return typeof l == r; }
}
if (!operators[operator])
throw new Error("Handlerbars Helper 'compare' doesn't know the operator "+operator);
var result = operators[operator](lvalue,rvalue);
if( result ) {
return options.fn(this);
} else {
return options.inverse(this);
}
});
Source: http://doginthehat.com.au/2012/02/comparison-block-helper-for-handlebars-templates/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With