Login

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

Author:
leopd
Posted:
April 12, 2011
Language:
Python
Version:
1.2
Tags:
template-tag string-formatting
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. Support for {% macro %} tags in templates, version 2 by mludvig 7 years, 9 months ago
  2. Create new variables in templates by jmrbcu 7 years, 3 months ago
  3. ajax protocol for data by limodou 8 years, 2 months ago
  4. ExprTag - Calculating python expression and saving the result to a variable by limodou 8 years, 2 months ago
  5. simple string formatting filter by gsf0 7 years, 8 months ago

Comments

Please login first before commenting.