register.tag as a class decorator

 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
27
28
29
30
31
32
33
34
35
36
37
import datetime
from django import template
register = template.Library()

if 1: # explicit tag name

    @register.tag('current_time')
    class CurrentTimeNode(template.Node):
        def __init__(self, parser, token):
            try:
                # split_contents() knows not to split quoted strings.
                tag_name, format_string = token.split_contents()
            except ValueError:
                raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
            if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
                raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
            self.format_string = str(format_string[1:-1])
            
        def render(self, context):
            return datetime.datetime.now().strftime(self.format_string)

else: # implicit tag name
    
    @register.tag
    class current_time(template.Node):
        def __init__(self, parser, token):
            try:
                # split_contents() knows not to split quoted strings.
                tag_name, format_string = token.split_contents()
            except ValueError:
                raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
            if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
                raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
            self.format_string = str(format_string[1:-1])
            
        def render(self, context):
            return datetime.datetime.now().strftime(self.format_string)

More like this

  1. Template Tag Render Decorator by stephen_mcd 4 years, 1 month ago
  2. Subdirectory and subcontext include template tag with examples by t_rybik 4 years, 1 month ago
  3. inclusion tag with template as variable by forgems 5 years, 2 months ago
  4. Parsing Tag decorator by pgcd 3 years, 11 months ago
  5. Language aware cache decorator by bartTC 4 years, 11 months ago

Comments

culebron (on June 21, 2010):

I see one disadvantage: can't inherit from a decorated class. This makes it impossible to reuse them. So, unless Library.tag is modified to handle classes as well, its use is limited. Except for that works perfect.

#

(Forgotten your password?)