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. LazyPrimaryKeyRelatedField by LLyaudet 6 days, 4 hours ago
  2. CacheInDictManager by LLyaudet 6 days, 11 hours ago
  3. MYSQL Full Text Expression by Bidaya0 1 week ago
  4. Custom model manager chaining (Python 3 re-write) by Spotted1270 1 week, 6 days ago
  5. Django Standard API Response Middleware for DRF for modern frontend easy usage by Denactive 4 weeks, 1 day ago

Comments

Please login first before commenting.