python - Flask Jinja 模板 - 将字符串格式化为货币
问题描述
有没有办法在 Flask 模板中将字符串格式化为货币 (USD)?
示例:mystring = "10000"
我想要的结果是:mynewstring = "$10,000.00"
解决方案
Jinja2 提供了一种格式化传递给模板的值的方法。它被称为自定义模板过滤。
从数字字符串显示模板中的货币格式:
- 在 Flask 应用程序中创建自定义过滤器
- 在模板中调用过滤器。自定义过滤器的详细信息可以在 官方文档中找到。
您可以使用字符串格式将字符串或语言环境格式化为@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>
输出:
推荐阅读
- office-js - Outlook 加载项停止工作,因为 Outlook Web 界面想要使用被浏览器阻止的对话框来确认域
- javascript - React Native Redux 不更新布尔值
- wordpress - 赛普拉斯断言颜色
- wordpress - 使用 Wordpress REST API 连接 WPML 页面
- javascript - 在 2020 年,我是否需要在第二次初始化时调用“removeEventListener”?
- kubernetes - Fluentd 无法将日志写入 /fluentd/log 目录
- powershell - 更改 powershell 对象中的嵌套对象值
- python - 如何将两个列表连接到 Pandas DataFrame 中?
- powershell - Publish-AzWebApp 引发错误
- reactjs - 使用 cypress 处理 React 重新渲染