Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pint formatting template tag #10

Open
tgs opened this issue Aug 28, 2018 · 1 comment
Open

Pint formatting template tag #10

tgs opened this issue Aug 28, 2018 · 1 comment

Comments

@tgs
Copy link

tgs commented Aug 28, 2018

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!

@CarliJoy
Copy link
Owner

CarliJoy commented Nov 29, 2020

Sound like a great idea.
Actually it would be easy to implement (in a safe way) - I will have a look into it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants