1 from django import template
2 from django.conf import settings
3 from django.contrib.sites.models import Site
6 register = template.Library()
9 class NodeURLNode(template.Node):
10 def __init__(self, node, with_obj, as_var):
12 self.node = template.Variable(node)
16 if with_obj is not None:
17 self.with_obj = template.Variable(with_obj)
23 def render(self, context):
26 node = self.node.resolve(context)
28 node = context['node']
29 current_site = Site.objects.get_current()
30 if node.has_ancestor(current_site.root_node):
31 url = '/' + node.get_path(root=current_site.root_node)
33 with_obj = self.with_obj.resolve(context)
34 subpath = node.view.get_subpath(with_obj)
39 return settings.TEMPLATE_STRING_IF_INVALID
42 context[self.as_var] = url
43 return settings.TEMPLATE_STRING_IF_INVALID
47 return settings.TEMPLATE_STRING_IF_INVALID
50 @register.tag(name='node_url')
51 def do_node_url(parser, token):
53 {% node_url [<node>] [with <obj>] [as <var>] %}
55 params = token.split_contents()
62 remaining_tokens = params[1:]
63 while remaining_tokens:
64 option_token = remaining_tokens.pop(0)
65 if option_token == 'with':
67 with_obj = remaining_tokens.pop(0)
69 raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument specifying an object handled by the view on the node' % tag)
70 elif option_token == 'as':
72 as_var = remaining_tokens.pop(0)
74 raise template.TemplateSyntaxError('"%s" template tag option "as" requires an argument specifying a variable name' % tag)
77 return NodeURLNode(node=node, with_obj=with_obj, as_var=as_var)
79 raise template.TemplateSyntaxError('"%s" template tag cannot accept more than five arguments' % tag)