Formats a django variable using a python string formatting as specified
in another template variable. Similar to |stringformat.
Takes two arguments: the django template variable with the item to be formatted
and the django template variable containing the format string.
{% pyformat number formatstringvar %}
Place this file in appname/templatetags/pyformat.py
and you're good.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | from django import template
from django.conf import settings
class PyFormatNode(template.Node):
def __init__(self, variable, format_str):
self.variable = variable
self.format_str = format_str
def render(self, context):
try:
var = self.variable.resolve(context)
format = self.format_str.resolve(context)
return format % var
except:
if settings.TEMPLATE_DEBUG:
raise
return ''
def do_pyformat(parser, token):
tag_name, variable, format_str = token.split_contents()
return PyFormatNode(parser.compile_filter(variable),
parser.compile_filter(format_str),
)
register = template.Library()
register.tag('pyformat', do_pyformat)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.