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

 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. simple string formatting filter by gsf0 5 years, 9 months ago
  2. Field List Tag by hughsaunders 2 years ago
  3. A templatetag to insert the output of another view (or local URL) by jamesgpearce 3 years, 11 months ago
  4. Partial Tag by mnbayazit 2 years, 10 months ago
  5. DaGood breadcrumbs by drozzy 4 years, 4 months ago

Comments

(Forgotten your password?)