Is there an easier/shorter way to filter this kind of code in Django's template?
-
27-05-2021 - |
Question
In my template, I have
Vendor:
{% if order.vendor %}
{{ order.vendor.name }}
{% else %}
Not assigned yet.
{% endif %}<br />
Quote:
{% if order.quote %}
${{ order.quote }}
{% else %}
No quote yet.
{% endif %}<br />
I know I could probably do a simplier version with {{ value|default:"nothing" }}
, but how would that apply to the 2nd case with Quote? Because the default version should also hide the $
. Otherwise it will say $No quote yet.
. Hmmm... maybe there is a way to use the Django's humanize
framework with $ symbols?
Solution
Well depending on how your values are stored for order.quote I'd probably personally approach this with a custom filter and replace it with something like {{ order.quote|currency|default:"No quote yet" }}
Where currency is a custom template filter defined (roughly) like:
import decimal
@register.filter
def currency(val):)
try:
return '$%s' % cents / decimal.Decimal(100.00)
except TypeError:
return ''
This of course assume you are storing quotes as integers rather than floats. Some localization could be thrown in as well for non US values
OTHER TIPS
You're already doing it the right way.