有没有办法在 Flask 模板中将字符串格式化为货币(美元)?
示例:mystring = "10000"
我想要的结果是: mynewstring = "$10,000.00"
Jinja2 提供了一种格式化传递给模板的值的方法。它被称为自定义模板过滤。
从数字字符串在模板中显示货币格式:
您可以使用字符串格式将字符串或语言环境格式化为@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)
Run Code Online (Sandbox Code Playgroud)
currency.html:
<html>
<head>
<title>Locale Example</title>
</head>
<body>
<h3>Locale Example</h3>
{% if data %}
<div>{{ data | currencyFormat }}</div>
{% endif %}
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
输出: