Sotan 666 django template tag

 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
38
import re
from django import template
register = template.Library()
class TagExecutor(template.Node):
def __init__(self, var_name, tag_itself):
self.tmpl = template.Template(u'{% ' + tag_itself + ' %}')
self.var_name = var_name
def render(self, context):
result = self.tmpl.render(template.Context({}))
context[self.var_name] = result
return ''
@register.tag
def get_var_from_tag(parser, token):
'''
Get tag result to variable.
Usage::
{% get_var_from_tag to url from url just.some.view %}
Part after `from` can be any (it will be executed as template tag with no context).
'''
try:
tag_name, arg = token.contents.split(None, 1)
except ValueError:
raise template.TemplateSyntaxError("%r tag requires arguments" % token.contents.split()[0])
m = re.search(r'^to (\w+) from (.*)$', arg)
if not m:
raise template.TemplateSyntaxError("%r tag had invalid arguments" % tag_name)
var_name, tag_itself = m.groups()
return TagExecutor(var_name, tag_itself)