Code

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

File django-include-tag-2.diff, 2.1 KB (added by rjwittams, 9 years ago)

updated patch - moved tag to template/loaders.py along with other loader tags.

Line 
1Index: django/core/template/loader.py
2===================================================================
3--- django/core/template/loader.py      (revision 880)
4+++ django/core/template/loader.py      (working copy)
5@@ -160,6 +160,34 @@
6                 parent_block.nodelist = block_node.nodelist
7         return compiled_parent.render(context)
8 
9+class ConstantIncludeNode(Node):
10+    def __init__(self, template_path):
11+        try:
12+            t = get_template(template_path)
13+            self.nodelist = t.nodelist
14+        except Exception, e:
15+            self.nodelist = None
16+
17+    def render(self, context):
18+        if self.nodelist:
19+            return self.nodelist.render(context)
20+        else:
21+            return ''
22+
23+class IncludeNode(Node):
24+    def __init__(self, template_path_var):
25+        self.template_path_var = template_path_var
26+
27+    def render(self, context):
28+         try:
29+             template_path = resolve_variable(self.template_path_var, context)
30+             print "IncludeNode rendering %s" % template_path
31+             t = template_loader.get_template(template_path)
32+             return t.render(context)
33+         except Exception, e:
34+             return '' # Fail silently for invalid included templates.
35+
36+
37 def do_block(parser, token):
38     """
39     Define a block that can be overridden by child templates.
40@@ -202,5 +230,19 @@
41         raise TemplateSyntaxError, "'%s' cannot appear more than once in the same template" % bits[0]
42     return ExtendsNode(nodelist, parent_name, parent_name_var)
43 
44+def do_include(parser, token):
45+    """
46+    Loads a template using standard resolution mechanisms, and renders it in the current context.
47+    """
48+    bits = token.contents.split()
49+    if len(bits) != 2:
50+        raise TemplateSyntaxError, "'include' tag takes one argument: the path to the template to be included"
51+
52+    path = bits[1]
53+    if path[0] in ('"', "'") and path[-1] == path[0]:
54+        return ConstantIncludeNode(path[1:-1])
55+    return IncludeNode(bits[1])
56+
57 register_tag('block', do_block)
58 register_tag('extends', do_extends)
59+register_tag('include', do_include)