Skip to main content
 首页 » 编程设计

python之Flask Jinja 模板之将字符串格式化为货币

2025年05月04日33kevingrace

有没有办法在 Flask 模板中将字符串格式化为货币 (USD)?

例子: mystring = "10000"

我想要的结果是:mynewstring = "$10,000.00"

请您参考如下方法:

Jinja2 提供了一种格式化传递给模板的值的方法。它被称为自定义模板过滤。

从数字字符串在模板中显示货币格式:

  • 在 Flask 应用中创建自定义过滤器
  • 调用模板中的过滤器。有关自定义过滤器的详细信息,请参见 official documentation here .

您可以使用字符串格式化来格式化字符串或 Locale 作为@Blitzer 的答案。 由于@Blitzer 已经提供了 locale 用法,我将在自定义过滤器中添加字符串格式。

app.py:

from flask import Flask, render_template 
app = Flask(__name__) 
 
@app.template_filter() 
def currencyFormat(value): 
    value = float(value) 
    return "${:,.2f}".format(value) 
 
@app.route('/') 
def home(): 
    data = "10000" 
    return render_template("currency.html", data=data) 
 
app.run(debug=True) 

currency.html:

<html> 
    <head> 
        <title>Locale Example</title> 
    </head> 
    <body> 
        <h3>Locale Example</h3> 
        {% if data %} 
            <div>{{ data | currencyFormat }}</div>             
        {% endif %} 
    </body> 
</html> 

输出: