简体   繁体   English

车把功能可使用JavaScript格式化货币

[英]Handlebars function to format currency with javascript

I have this in my handlebar template: 我的车把模板中有这个:

<span class="currencyFormatMe">{{_current_price}}</span>

An example of what the loop returns|: Bid: $24000 循环返回的示例|: 出价:$ 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, "$1,") ); 
    })
}

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, "$1,") ); 
        })
    }
);

Calling: 致电:

{{formatCurrency _current_price}}

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; 您可以坚持使用jQuery插件,并在填写了Handlebars模板后应用它; something like this: 像这样的东西:

<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, "$1,") ); 
    })
};

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. 或者,您可以将插件转换为Handlebars帮助器,然后在模板中进行格式化。 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. 如果要执行此操作,则只需格式化传递给帮助程序的值,而不用弄乱辅助程序内的$(this) For example: 例如:

<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, "$1,");
});

var t = Handlebars.compile($('#t').html());
var h = t({
    _current_price: 1000
});

Demo: http://jsfiddle.net/ambiguous/5b6vh/ 演示: http//jsfiddle.net/ambiguous/5b6vh/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM