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?
Mustache is a logic-less template syntax. It can be used for HTML, config files, source code - anything. It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops.
With JQuery's html method, we get the template data. var text = Mustache. render(template, data); The output is rendered with Mustache.
Partials are Mustache template files that are included in a page, similar to an include, import, or a nested template.
Mustache is a logic-less templating system. It permits you to use pre-written text files with placeholders that will be replaced at run-time with values particular to a given request. For more general information on Mustache, consult the mustache specification.
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.
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