Handlebar If Condition Not Working
Unable to use if condition in Handlbars template. Below is my jquery Handlebars function below, $.each(data.response, function (i, item) { var source = $('#my-orders').html();
Solution 1:
This is a misunderstanding of the if condition. Look at the #if documentation here : http://handlebarsjs.com/builtin_helpers.html
You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.
What you need to do is a handlebar helper to test your condition.
Here is one example of a "test" helper that I use to do comparisons :
Handlebars.registerHelper('test', function(lvalue, operator, rvalue, options) {
var doDisplay = false;
var items = (""+rvalue).split("|");
var arrayLength = items.length;
for (var i = 0; (i < arrayLength); i++) {
if (operator == "eq") {
if (lvalue == items[i]) {
doDisplay = true;
}
} elseif (operator == "ne") {
if (lvalue != items[i]) {
doDisplay = true;
}
} elseif (operator == "gt") {
if (parseFloat(lvalue) > parseFloat(items[i])) {
doDisplay = true;
}
} elseif (operator == "lt") {
if (parseFloat(lvalue) < parseFloat(items[i])) {
doDisplay = true;
}
}elseif (operator == "le") {
if (parseFloat(lvalue) <= parseFloat(items[i])) {
doDisplay = true;
}
}elseif (operator == "ge") {
if (parseFloat(lvalue) >= parseFloat(items[i])) {
doDisplay = true;
}
}
}
if (doDisplay) {
return options.fn(this);
} else {
return"";
}
});
and here is how you call it for example if you and to test and display a result depending on the test:
{{#test id 'eq' '1'}}
{{id}} equals 1
{{/test}}
{{#test id 'ne' '1'}}
{{id}} do not equals 1
{{/test}}
{{#test id 'ge' '1'}}
{{id}} greater or equals 1
{{/test}}
{{#test id 'ne' '1'}}
{{id}} lower or equals 1
{{/test}}
Post a Comment for "Handlebar If Condition Not Working"