【问题标题】:Handlebars function to format currency with javascriptHandlebars 函数使用 javascript 格式化货币
【发布时间】:2013-01-24 11:40:07
【问题描述】:

我的车把模板中有这个:

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

循环返回的示例|:出价:24000 美元

我想用逗号格式化它,但我失败了。

我有这个在控制台中工作的功能,但在适应带有把手的代码库时失败。

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

我称之为 $("span.currencyFormatMe").digits();

再次,这一切都在控制台中工作,但在适应时失败。任何指针都非常欢迎

用 registerhelper 尝试过:

Handlebars.registerHelper('formatCurrency',
    $.fn.digits = function(){ 
        return this.each(function(){ 
            $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
        })
    }
);

调用:

{{formatCurrency _current_price}}

【问题讨论】:

  • 你不应该使用 registerHelper
  • @epascarello 更新了上面的代码以反映我对助手的尝试......仍然没有运气。有什么突出的吗?

标签: javascript jquery string-formatting handlebars.js


【解决方案1】:

这里有几个简单的选项。

您可以坚持使用您的 jQuery 插件,并在 Handlebars 模板填写完毕后应用它;像这样:

<script id="t" type="text/x-handlebars">
    <span class="currencyFormatMe">{{_current_price}}</span>
</script>

然后:

$.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();

演示:http://jsfiddle.net/ambiguous/732uN/

或者您可以将您的插件转换为 Handlebars 助手并在模板中进行格式化。如果你想这样做,你只需要格式化传递给帮助器的值,而不是在帮助器中弄乱$(this)。例如:

<script id="t" type="text/x-handlebars">
    {{formatCurrency _current_price}}
</script>

然后:

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
});

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

【讨论】:

  • 感谢以上内容,但它不能处理例如 24000.50 美元的出价。对这部分有什么建议吗?
  • @TaiHirabayashi 您是指.50 部分吗?可能最好寻找一个 prinft JavaScript 库并将其包装在 Handlebars 助手中。
  • 使用以下语法不会去除尾随零:${{{price}}}
猜你喜欢
  • 1970-01-01
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
  • 2011-09-16
  • 1970-01-01
  • 2011-03-21
  • 1970-01-01
相关资源
最近更新 更多