首页 > 解决方案 > Flask Jinja 模板 - 将字符串格式化为货币

问题描述

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

示例:mystring = "10000"

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

标签: pythonflask

解决方案


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>

输出:

Flask 自定义过滤的输出


推荐阅读