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)
Comments
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.
#