我正在尝试设置一个 mustache.js 模板,该模板使用 lambda 将数字格式化为特定的小数位,但我遇到了问题。给定一个看起来像这样的对象:
{
x: 123,
points: [
{ name: "foo", y: 1.234567 },
{ name: "bar", y: 2.123456 },
{ name: "fax", y: 3.623415 }
]
}
首先,我尝试设置一个如下所示的模板:
var template = "{{x}}{{#points}}<br/>{{name}}, {{#y.toFixed}}2{{/y.toFixed}}";
这没有用(在应该是数字的地方生成了一个空白空间。我想也许 lambda 的格式不正确,因为 toFixed 不返回函数 ( mustache docs )。所以我尝试了:
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}}"
再次失败。我什至尝试将 toMustacheFixed 函数简化为:
Number.prototype.toMustacheFixed = function(){
return function(){ return 123.45; };
};
这没有帮助。我在模板中仍然是一片空白。那么,Mustache.js 是否可以不处理数字上的原生函数和原型(prototype)函数,还是我做错了什么?
最佳答案
这样试试:http://jsfiddle.net/QXFY4/10/
我完成了你的部分:{{/points}}
我在 http://mustache.github.com/mustache.5.html 的 Lambdas 部分添加了一个函数 toFixed
对应的示例
有了这个,我能够通过解析 float 并在其上调用 toFixed 来更改 {{y}}
的渲染。
关于javascript - Mustache.js lambdas 和数字格式化 toFixed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12161837/