Is it possible to do calculations in mustache.js templates?
I want to multiple a value called ratio
by a fixed amount e.g. 240
My tag looks like this:
<div><img src="https://s3.amazonaws.com/com.myapp.demo/{{url}}" class="item" style="height:{{ratio * 240}}"></div>
Since the url
value is displayed correctly, I feel it must be the calculation that is causing me trouble.
You can do this using a function:
template:
<div>
<img src="https://s3.amazonaws.com/com.myapp.demo/{{url}}"
class="item" style="height:{{#ratio}} {{x240Times}} {{/ratio}}">
</div>
code:
Mustache.render(template,{
ratio: 2,
x240Times: function() {
return this.ratio * 240;
}
});
You could also use my extension mustache-wax to use formatters in your templates, for example:
Define a "multiply" formatter which accepts one argument:
Mustache.Formatters = {
"multiply": function (value, multiplier) {
return value * multiplier;
}
}
Use it in your template:
<div>
<img src="https://s3.amazonaws.com/com.myapp.demo/{{url}}"
class="item" style="height:{{ratio | multiply:240}}">
</div>
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