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

时间:2019-04-03 20:10:05

标签: python flask

是否可以在Flask模板中将字符串格式转换为货币(USD)?

示例:     mystring =“ 10000”

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

2 个答案:

答案 0 :(得分:2)

您可以使用语言环境在Flask代码中进行转换

@app.template_filter('conv_curr')
def conv_curr(amount): 
  import locale 
  locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') 
  return locale.currency(amount)

然后使用过滤器

{{ 10000|conv_curr }}

答案 1 :(得分:1)

Jinja2提供了一种格式化传递给模板的值的方法。这就是自定义模板过滤

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

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

您可以使用字符串格式将字符串或语言环境格式化为@Blitzer的答案。 由于@Blitzer已经提供了TYPE ARRAY的用法,因此我将字符串格式添加到自定义过滤器中。

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

输出:

output of Flask custom filtering

相关问题