使用 javascript 格式化货币的 Handlebars 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14492098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handlebars function to format currency with javascript
提问by jahrichie
I have this in my handlebar template:
我的车把模板中有这个:
<span class="currencyFormatMe">{{_current_price}}</span>
An example of what the loop returns|: Bid: $24000
循环返回的示例|:Bid: $24000
I'd like to format that with commas and i'm failing.
我想用逗号格式化它,但我失败了。
I have this function which works in the console, but fails when adapted to the codebase with handlebars.
我有这个在控制台中工作的功能,但在适应带有把手的代码库时失败。
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ",") );
})
}
And I call it like $("span.currencyFormatMe").digits();
我称之为 $("span.currencyFormatMe").digits();
Again it all works in the console, but fails when adapted. Any pointers are very welcome
同样,这一切都在控制台中工作,但在适应时失败。任何指针都非常欢迎
Tried it with a registerhelper:
用 registerhelper 试了一下:
Handlebars.registerHelper('formatCurrency',
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ",") );
})
}
);
Calling:
调用:
{{formatCurrency _current_price}}
回答by mu is too short
You have a couple simple options here.
您在这里有几个简单的选择。
You can stick with your jQuery plugin and apply it after the Handlebars template has been filled in; something like this:
您可以坚持使用您的 jQuery 插件,并在填写 Handlebars 模板后应用它;像这样:
<script id="t" type="text/x-handlebars">
<span class="currencyFormatMe">{{_current_price}}</span>
</script>
and then:
接着:
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ",") );
})
};
var t = Handlebars.compile($('#t').html());
var h = t({
_current_price: 1000
});
$('<div>').append(h).find('.currencyFormatMe').digits();
Demo: http://jsfiddle.net/ambiguous/732uN/
演示:http: //jsfiddle.net/ambiguous/732uN/
Or you can convert your plugin into a Handlebars helper and do the formatting in the template. If you want to do this you just have to format the value passed to the helper rather than messing around with $(this)
inside the helper. For example:
或者您可以将您的插件转换为 Handlebars 助手并在模板中进行格式化。如果你想这样做,你只需要格式化传递给助手的值,而不是$(this)
在助手内部乱搞。例如:
<script id="t" type="text/x-handlebars">
{{formatCurrency _current_price}}
</script>
and then:
接着:
Handlebars.registerHelper('formatCurrency', function(value) {
return value.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, ",");
});
var t = Handlebars.compile($('#t').html());
var h = t({
_current_price: 1000
});