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();
var template = Handlebars.compile(source);
html += template(item);
//alert(html);
});
if(html){
$("#myorderss").html(html);
}
When I'm using if
condition, its not working.
{{#if id=='1'}}
{{/if}}
How to use if
condition in handlebars template?
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;
}
} else if (operator == "ne") {
if (lvalue != items[i]) {
doDisplay = true;
}
} else if (operator == "gt") {
if (parseFloat(lvalue) > parseFloat(items[i])) {
doDisplay = true;
}
} else if (operator == "lt") {
if (parseFloat(lvalue) < parseFloat(items[i])) {
doDisplay = true;
}
}else if (operator == "le") {
if (parseFloat(lvalue) <= parseFloat(items[i])) {
doDisplay = true;
}
}else if (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}}