5

I'm trying to set up a mustache.js template that formats a number to a specific decimal place using a lambda and I'm running into issues. Given an object that looks like:

{
     x: 123,
     points: [
          { name: "foo", y: 1.234567 },
          { name: "bar", y: 2.123456 },
          { name: "fax", y: 3.623415 }
     ]
}

First I tried setting up a template that looked like:

var template = "{{x}}{{#points}}<br/>{{name}}, {{#y.toFixed}}2{{/y.toFixed}}";

This didn't work (generated an empty space where the number should be. I though maybe the lambda wasn't in the correct format since toFixed does not return a function (mustache docs). So I tried:

Number.prototype.toMustacheFixed = function(){
     var n = this;
     return function(d){ return n.toFixed(d); };
};
var template = "{{x}}{{#points}}<br/>{{name}}, {{#y.toMustacheFixed}}2{{/y.toMustacheFixed}}"

Again, fail. I even tried simplifying the toMustacheFixed function to:

Number.prototype.toMustacheFixed = function(){
     return function(){ return 123.45; };
};

This didn't help. I was still getting a blank in the template. So, can Mustache.js just not handle native and prototype functions on numbers, or am I doing something wrong?

roto
  • 677
  • 6
  • 11

1 Answers1

11

Try it this way: http://jsfiddle.net/QXFY4/10/

I finished your section: {{/points}}

I added a function toFixed corresponding to the example in the Lambdas section at http://mustache.github.com/mustache.5.html

With this, I was able to change the rendering of {{y}} by parsing the float and calling toFixed on it.

SgtPooki
  • 11,012
  • 5
  • 37
  • 46
Royce Feng
  • 1,663
  • 1
  • 10
  • 6
  • Nice answer, I was going exactly for that and you nailed it better than what I was writing. – gonchuki Aug 28 '12 at 16:37
  • Nice. This is the same conclusion I reached as well (but didn't want to be that guy who answers his own question). Thanks! – roto Aug 28 '12 at 18:25