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 url += node.view.get_subpath(with_obj)
36 return settings.TEMPLATE_STRING_IF_INVALID
39 context[self.as_var] = url
40 return settings.TEMPLATE_STRING_IF_INVALID
44 return settings.TEMPLATE_STRING_IF_INVALID
47 @register.tag(name='node_url')
48 def do_node_url(parser, token):
50 {% node_url [<node>] [with <obj>] [as <var>] %}
52 params = token.split_contents()
59 remaining_tokens = params[1:]
60 while remaining_tokens:
61 option_token = remaining_tokens.pop(0)
62 if option_token == 'with':
64 with_obj = remaining_tokens.pop(0)
66 raise template.TemplateSyntaxError('"%s" template tag option "with" requires an argument specifying an object handled by the view on the node' % tag)
67 elif option_token == 'as':
69 as_var = remaining_tokens.pop(0)
71 raise template.TemplateSyntaxError('"%s" template tag option "as" requires an argument specifying a variable name' % tag)
74 return NodeURLNode(node=node, with_obj=with_obj, as_var=as_var)
76 raise template.TemplateSyntaxError('"%s" template tag cannot accept more than five arguments' % tag)