I\'m trying to format a float as comma-separated currency. E.g. 543921.9354
becomes $543,921.94
. I\'m using the format
filter in Jinja t
If you have Python 2.6 or newer:
You could write a custom filter for one purpose, but, as a broader solution, you could also update the format filter itself:
from jinja import Environment, FileSystemLoader
def format(fmt_str, *args, **kwargs):
if args and kwargs:
raise jinja2.exceptions.FilterArgumentError(
"can't handle positional and keyword "
"arguments at the same time"
)
ufmt_str = jinja2.utils.soft_unicode(fmt_str)
if kwargs:
return ufmt_str.format(**kwargs)
return ufmt_str.format(*args)
env = Environment(loader=FileSystemLoader('./my/template/dir'))
env.filters.update({
'format': format,
})
This will replace the existing format
filter (as of Jinja 2.7.1). The majority of the function was ripped straight from the format source. The only difference between this function and jinja's is that it uses the str.format() function to format the string.
Seeing that Jinja2 (at the time of this writing) no longer supports Python 2.5, I bet it won't be long before the format
filter uses Python's str.format().