Skip to content

Instantly share code, notes, and snippets.

@FrankFang
Created September 18, 2013 03:04
Show Gist options
  • Save FrankFang/6603970 to your computer and use it in GitHub Desktop.
Save FrankFang/6603970 to your computer and use it in GitHub Desktop.
Handlebars Math.
Handlebars.registerHelper("math", function(lvalue, operator, rvalue, options) {
if (arguments.length < 4) {
// Operator omitted, assuming "+"
options = rvalue;
rvalue = operator;
operator = "+";
}
lvalue = parseFloat(lvalue);
rvalue = parseFloat(rvalue);
return {
"+": lvalue + rvalue,
"-": lvalue - rvalue,
"*": lvalue * rvalue,
"/": lvalue / rvalue,
"%": lvalue % rvalue
}[operator];
});
var rendered = Handlebars.compile(
'{{#each values}}' +
'[{{@index}}]: ' +
'i+1 = {{math @index 1}}, ' +
'i-0.5 = {{math @index "+" "-0.5"}}, ' +
'i/2 = {{math @index "*" 2}}, ' +
'i%2 = {{math @index "%" 2}}, ' +
'i*i = {{math @index "*" @index}}\n' +
'{{/each}}'
)({
values : [ 'a', 'b', 'c', 'd', 'e' ]
});
$("#result").html(rendered);
// http://jsfiddle.net/frankfang/Kp2VJ/
@devanddhiraj
Copy link

how do i perform operation like - ((data.response.MRP - data.response.sellingPrice)*100) /data.response.MRP

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment