I want display different HTML depending on a condition.
It doesn't seem to compare those two values and it always shows the first variant. How can I compare the predefined values to the original value from JSON so that it can execute properly?
{{#each this}}
{{#each visits}}
<div class="row">
{{#if variable_from_json }}
<div class="col-lg-2 col-md-2 col-sm-2">
<i class="fa fa-home"></i>
</div>
{{else}}
<div class="col-lg-2 col-md-2 col-sm-2">
<i class="fa fa-plus symbol-hospital"></i>
</div>
{{/if}}
</div>
{{/each}}
{{/each}}
JS code
Handlebars.registerHelper('if', function (variable_from_json, options) {
if (variable_from_json === "M") {
return options.fn(this);
} else {
return options.inverse(this);
}
});
To compare values like ==,>=,|| ,&& Create one helper which will handle all cases
Handlebars.registerHelper( "when",function(operand_1, operator, operand_2, options) {
var operators = {
'eq': function(l,r) { return l == r; },
'noteq': function(l,r) { return l != r; },
'gt': function(l,r) { return Number(l) > Number(r); },
'or': function(l,r) { return l || r; },
'and': function(l,r) { return l && r; },
'%': function(l,r) { return (l % r) === 0; }
}
, result = operators[operator](operand_1,operand_2);
if (result) return options.fn(this);
else return options.inverse(this);
});
Use this operator in handlebar file For eg. == operator
{{#when <operand1> 'eq' <operand2>}}
// do something here
{{/when}}
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