I need a way to compare values in handlebars and found this helper on the web:
Handlebars.registerHelper('compare', function(lvalue, rvalue, options) {
if (arguments.length < 3)
throw new Error("Handlerbars Helper 'compare' needs 2 parameters");
var 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);
}
This is how I use it:
{{#each numbers as |nr|}}
{{#compare nr stars operator="<=" }}
<span{{action "rate" }} class="rating{{nr}} glyphicon glyphicon-star"></span>
{{/compare}}
{{/each}}
});
I get this error:
TypeError: options.inverse is not a function
You need to define the else
section for compare block helper.
Handlebars provides the block for the else fragment as options.inverse. You do not need to check for the existence of the else fragment: Handlebars will detect it automatically.
Source: https://handlebarsjs.com/guide/block-helpers.html#conditionals