spideyclick
spideyclick

Reputation: 182

Django Template firstof + filter

I am using a Django template in my webapp, and am displaying values that are one of two things:

  1. Numbers (up to 2 digits float)
  2. The string "None"

What I'd like to do is:

  1. Change "None" to 0, if value is "None".
  2. Use Float Format to ensure value is displayed as 2nd digit float

Right now, I can do those separately:

{% firstof myValue 0.00 %}

(this outputs either the value or 0.00 if myValue = "None")

{{ myValue | floatformat:2 }}

(this formats the number to something like 2.70 for example, but doesn't change "None" to 0.00)

Is there a way to combine the functionality of those two?

Upvotes: 0

Views: 413

Answers (2)

ABN
ABN

Reputation: 1152

A simple and efficient way is to chain default_if and floatformat filters:

{{ myValue|default_if_none:0.00|floatformat:2 }}
  1. When

    myValue = "22"
    

    Output:

    22.00
    
  2. When

    myValue = None
    

    Output:

    0.00
    

Upvotes: 0

Konstantin
Konstantin

Reputation: 25339

Just use if

{% if myValue is None %}
  0.00
{% else %}
  {{ myValue | floatformat:2 }}
{% endif %}

Upvotes: 1

Related Questions