Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do a simple calculation in a mustache.js template

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.

like image 298
Ankur Avatar asked Oct 27 '12 04:10

Ankur


1 Answers

Option 1

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;
  }
});

Option 2

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>
like image 178
JVitela Avatar answered Nov 15 '22 23:11

JVitela