Code

Ticket #6544: django-allow-comments-before-extends.diff

File django-allow-comments-before-extends.diff, 1.8 KB (added by Bastian Kleineidam <calvin@…>, 6 years ago)
Line 
1commit dcbff38c016c824c5927b1f57385d19aad4157f3
2Author: Bastian Kleineidam <calvin@debian.org>
3Date:   Wed Feb 6 11:34:56 2008 +0100
4
5    Allow comments and whitespace before an {% extends %}
6   
7diff --git a/django/template/__init__.py b/django/template/__init__.py
8index 1772b89..c85f9fa 100644
9--- a/django/template/__init__.py
10+++ b/django/template/__init__.py
11@@ -303,12 +303,8 @@ class Parser(object):
12         return NodeList()
13 
14     def extend_nodelist(self, nodelist, node, token):
15-        if node.must_be_first and nodelist:
16-            try:
17-                if nodelist.contains_nontext:
18-                    raise AttributeError
19-            except AttributeError:
20-                raise TemplateSyntaxError("%r must be the first tag in the template." % node)
21+        if node.must_be_first and nodelist_extends_filter(nodelist):
22+            raise TemplateSyntaxError("%r must be the first tag in the template (preceding nodes: %s)" % (node, nodelist))
23         if isinstance(nodelist, NodeList) and not isinstance(node, TextNode):
24             nodelist.contains_nontext = True
25         nodelist.append(node)
26@@ -360,6 +356,21 @@ class Parser(object):
27         else:
28             raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name)
29 
30+
31+is_whitespace = re.compile(r"^\s+$").search
32+def nodelist_extends_filter (nodelist):
33+    """Filter ignorable nodes preceding a "extends" tag."""
34+    return filter(lambda x: not node_extends_ignore(x), nodelist)
35+
36+
37+def node_extends_ignore (node):
38+    """Determine if the contents of the node can be ignored preceding
39+    a "extends" tag."""
40+    from defaulttags import CommentNode
41+    return (isinstance(node, TextNode) and is_whitespace(node.s)) or \
42+           isinstance(node, CommentNode)
43+
44+
45 class TokenParser(object):
46     """
47     Subclass this and implement the top() method to parse a template line. When