Login

Simple template tag to do |stringformat filter with format from a variable

Author:
leopd
Posted:
April 12, 2011
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.