Generic Template Tag framework with context variable

svn: r13869
This commit is contained in:
Doug Blank 2009-12-21 02:53:31 +00:00
parent a17ae4c484
commit 05cc37cea7

View File

@ -30,33 +30,41 @@ def get_person_from_handle(db, handle):
return db.get_person_from_handle(handle) return db.get_person_from_handle(handle)
class TemplateNode(template.Node): class TemplateNode(template.Node):
def __init__(self, args, var_name): def __init__(self, args, var_name, func):
self.db = template.Variable(args[0]) self.args = map(template.Variable, args)
self.handle = template.Variable(args[1])
self.var_name = var_name self.var_name = var_name
self.func = func
def render(self, context): def render(self, context):
context[self.var_name] = \ value = self.func(*[item.resolve(context) for item in self.args])
get_person_from_handle(self.db.resolve(context), if self.var_name:
self.handle.resolve(context)) context[self.var_name] = value
return '' return ''
else:
return value
def do_get_person_from_handle(parser, token): def parse_tokens(tokens):
try: # Splitting by None splits by spaces
# Splitting by None == splitting by spaces. items = tokens.contents.split(None)
tag_name, args = token.contents.split(None, 1) # {% tag_name arg1 arg2 arg3 as variable %}
except ValueError: # {% tag_name arg1 arg2 arg3 %}
raise template.TemplateSyntaxError, \ tag_name = items[0]
("%r tag requires arguments" % token.contents.split()[0]) if "as" == items[-2]:
m = re.search(r'(.*?) as (\w+)', args) var_name = items[-1]
if not m: args = items[1:-2]
raise template.TemplateSyntaxError, \ else:
("%r tag had invalid arguments" % tag_name) var_name = None
args_string, var_name = m.groups() args = items[1:]
args = args_string.split() return (tag_name, args, var_name)
return TemplateNode(args, var_name)
register.tag("get_person_from_handle", do_get_person_from_handle) def make_tag(func):
def do_func(parser, tokens):
tag_name, args, var_name = parse_tokens(tokens)
return TemplateNode(args, var_name, func)
return do_func
register.tag("get_person_from_handle",
make_tag(get_person_from_handle))
probably_alive.is_safe = True probably_alive.is_safe = True
register.filter('probably_alive', probably_alive) register.filter('probably_alive', probably_alive)