Code

Ticket #598: django-include-tag-svn880.diff

File django-include-tag-svn880.diff, 2.4 KB (added by L.Plant.98@…, 9 years ago)

Patch updated for subversion rev 880 plus

Line 
1Index: django/core/template/defaulttags.py
2===================================================================
3--- django/core/template/defaulttags.py (revision 882)
4+++ django/core/template/defaulttags.py (working copy)
5@@ -227,6 +227,36 @@
6                 return '' # Fail silently for invalid included templates.
7         return output
8 
9+class ConstantIncludeNode(Node):
10+    def __init__(self, template_path):
11+        from django.core.template.loader import get_template
12+        try:
13+            t = get_template(template_path)
14+            self.nodelist = t.nodelist
15+        except Exception, e:
16+            self.nodelist = None
17+
18+    def render(self, context):
19+        if self.nodelist:
20+            return self.nodelist.render(context)
21+        else:
22+            return ''
23+
24+class IncludeNode(Node):
25+   
26+    def __init__(self, template_path_var):
27+        self.template_path_var = template_path_var
28+
29+    def render(self, context):
30+        from django.core.template.loader import get_template
31+        try:
32+            template_path = template.resolve_variable(self.template_path_var, context)
33+            print "IncludeNode rendering %s" % template_path
34+            t = get_template(template_path)
35+            return t.render(context)
36+        except Exception, e:
37+            return '' # Fail silently for invalid included templates.
38+
39 class LoadNode(Node):
40     def __init__(self, taglib):
41         self.taglib = taglib
42@@ -608,6 +638,19 @@
43             raise TemplateSyntaxError, "Second (optional) argument to %s tag must be 'parsed'" % bits[0]
44     return SsiNode(bits[1], parsed)
45 
46+def do_include(parser, token):
47+    """
48+    Loads a template using standard resolution mechanisms, and renders it in the current context.     
49+    """
50+    bits = token.contents.split()
51+    if len(bits) != 2:
52+        raise TemplateSyntaxError, "'include' tag takes one argument: the path to the template to be included"
53+   
54+    path = bits[1]
55+    if path[0] in ('"', "'") and path[-1] == path[0]:
56+        return ConstantIncludeNode(path[1:-1])
57+    return IncludeNode(bits[1])
58+
59 def do_load(parser, token):
60     """
61     Load a custom template tag set.
62@@ -763,6 +806,7 @@
63 register_tag('ifnotequal', lambda parser, token: do_ifequal(parser, token, True))
64 register_tag('if', do_if)
65 register_tag('ifchanged', do_ifchanged)
66+register_tag('include', do_include)
67 register_tag('regroup', do_regroup)
68 register_tag('ssi', do_ssi)
69 register_tag('load', do_load)