django-pint
django-pint copied to clipboard
Pint formatting template tag
Pint has special string formatting support. For example, from the docs:
>>> accel = 1.3 * ureg['meter/second**2']
>>> 'The HTML representation is {:H}'.format(accel)
'The HTML representation is 1.3 meter/second<sup>2</sup>'
I added this file as myapp/templatetags/pint_fmt.py
:
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def pint(value, fmt):
full_fmt = '{:' + fmt + '}'
return mark_safe(full_fmt.format(value))
Now I can do this in my templates:
{% load pint_fmt %}
{{ my_model.distance_field|pint:".2H" }}
And it gives me my field with two decimal places, and renders the units in HTML.
I haven't thought through the security implications of the mark_safe (my web site will be used by only me), and I don't know if you like the details of this way of getting at the formatting code, but I thought you might want to think about it.
Thanks for django-pint, it's great - exactly what I needed!
Sound like a great idea. Actually it would be easy to implement (in a safe way) - I will have a look into it.