我正在使用handlebars.js,我想用一个助手格式化一些数字。为了格式化一个数字,我找到了一个似乎符合我期望的accounting.js库。要格式化我可以使用的数字:
// Simple `format` string allows control of symbol position (%v = value, %s = symbol):
accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP这是我目前的助手:
Handlebars.registerHelper('amount', function(item) {
if (item == null) {
return "-";
} else {
return accounting.formatMoney(item,{symbol: "EUR", format: "%v %s"});
}
});这是可行的,但这有点严格的使用,我希望能够格式化我的数字作为一种选择。我的新帮手将是:
Handlebars.registerHelper('amount', function(item, options) {
if (item == null) {
return "-";
} else {
return accounting.formatMoney(item,options);
}
});问题是它不能工作,因为我不知道如何将对象传递给工作人员。这是我在模板中的调用
{{amount programme.amountIssued {symbol: "EUR", format: "%v %s"} }}这给了我以下结果:
handlebars.js:1659 Uncaught Error: Parse error on line 87:
...gramme.amountIssued {symbol: "EUR", for
-----------------------^
Expecting 'CLOSE_RAW_BLOCK', 'CLOSE', 'CLOSE_UNESCAPED', 'OPEN_SEXPR', 'CLOSE_SEXPR', 'ID', 'OPEN_BLOCK_PARAMS', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', 'SEP', got 'INVALID'如果我把它和引号放在一起用\:
{{amount programme.amountIssued "{symbol: \"EUR\", format: \"%v %s\"}" }}这是执行的,但结果并不是预期的结果:
{symbol: "EUR", format: "4,000,000,000.00 %s"}%v而不是4,000,000.00欧元
发布于 2016-04-26 08:28:46
不能将参数传递给带有对象的JS函数。但是你可以把它们作为数组传递。这是通过.apply (文档)完成的。
包装以便于阅读,并包括每个选项的默认值:
Handlebars.registerHelper('amount', function (item, options) {
if (item == null) return "-";
return accounting.formatMoney.apply(accounting, [
item,
options.symbol || "",
options.precision || 2,
options.thousands || ".",
options.decimal || ","
]);
});在这里,函数被应用到一个值数组(因此是操作的名称),其中每个数组位置都与函数所期望的参数位置匹配。
https://stackoverflow.com/questions/36859097
复制相似问题