Chris Curvey
Chris Curvey

Reputation: 10389

jinja format strings that could be "None"

I'm getting started with Jinja by converting my Django templates. Let's say I have a variable that represents a dollar value. So if I want to format it to two decimal places, I would do this:

{{"%.2f" | format(my_dollar_var)}}

But what if my_dollar_var is None? In that case, I'd like to show something else (like a question mark or a dash -- but not a zero).

Upvotes: 0

Views: 985

Answers (1)

Andrew Kloos
Andrew Kloos

Reputation: 4598

I use a customer Currency filter:

 def Currency(value):
     if(value == None):
          return "???"
     else:
          return "${:,.2f}".format(float(value))

jinja2.filters.FILTERS['Currency'] = Currency

Then just use:

{{ PRICE | Currency }}

Hope this helps!

Upvotes: 1

Related Questions