Debian Codegraph @

django/template/loader_tags.py

raw
1 import posixpath
2 from collections import defaultdict
3
4 from django.utils.safestring import mark_safe
5
6 from .base import Node, Template, TemplateSyntaxError, TextNode, Variable, token_kwargs
7 from .library import Library
8
9 register = Library()
10
11 BLOCK_CONTEXT_KEY = "block_context"
12
13
14 class BlockContext:
15 def __init__(self):
16 # Dictionary of FIFO queues.
17 self.blocks = defaultdict(list)
18
19 def __repr__(self):
20 return f"<{self.__class__.__qualname__}: blocks={self.blocks!r}>"
21
22 def add_blocks(self, blocks):
23 for name, block in blocks.items():
24 self.blocks[name].insert(0, block)
25
26 def pop(self, name):
27 try:
28 return self.blocks[name].pop()
29 except IndexError:
30 return None
31
32 def push(self, name, block):
33 self.blocks[name].append(block)
34
35 def get_block(self, name):
36 try:
37 return self.blocks[name][-1]
38 except IndexError:
39 return None
40
41
42 class BlockNode(Node):
43 def __init__(self, name, nodelist, parent=None):
44 self.name = name
45 self.nodelist = nodelist
46 self.parent = parent
47
48 def __repr__(self):
49 return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist)
50
51 def render(self, context):
52 block_context = context.render_context.get(BLOCK_CONTEXT_KEY)
53 with context.push():
54 if block_context is None:
55 context["block"] = self
56 result = self.nodelist.render(context)
57 else:
58 push = block = block_context.pop(self.name)
59 if block is None:
60 block = self
61 # Create new block so we can store context without thread-safety issues.
62 block = type(self)(block.name, block.nodelist)
63 block.context = context
64 context["block"] = block
65 result = block.nodelist.render(context)
66 if push is not None:
67 block_context.push(self.name, push)
68 return result
69
70 def super(self):
71 if not hasattr(self, "context"):
72 raise TemplateSyntaxError(
73 "'%s' object has no attribute 'context'. Did you use "
74 "{{ block.super }} in a base template?" % self.__class__.__name__
75 )
76 render_context = self.context.render_context
77 if (
78 BLOCK_CONTEXT_KEY in render_context
79 and render_context[BLOCK_CONTEXT_KEY].get_block(self.name) is not None
80 ):
81 return mark_safe(self.render(self.context))
82 return ""
83
84
85 class ExtendsNode(Node):
86 must_be_first = True
87 context_key = "extends_context"
88
89 def __init__(self, nodelist, parent_name, template_dirs=None):
90 self.nodelist = nodelist
91 self.parent_name = parent_name
92 self.template_dirs = template_dirs
93 self.blocks = {n.name: n for n in nodelist.get_nodes_by_type(BlockNode)}
94
95 def __repr__(self):
96 return "<%s: extends %s>" % (self.__class__.__name__, self.parent_name.token)
97
98 def find_template(self, template_name, context):
99 """
100 This is a wrapper around engine.find_template(). A history is kept in
101 the render_context attribute between successive extends calls and
102 passed as the skip argument. This enables extends to work recursively
103 without extending the same template twice.
104 """
105 history = context.render_context.setdefault(
106 self.context_key,
107 [self.origin],
108 )
109 template, origin = context.template.engine.find_template(
110 template_name,
111 skip=history,
112 )
113 history.append(origin)
114 return template
115
116 def get_parent(self, context):
117 parent = self.parent_name.resolve(context)
118 if not parent:
119 error_msg = "Invalid template name in 'extends' tag: %r." % parent
120 if self.parent_name.filters or isinstance(self.parent_name.var, Variable):
121 error_msg += (
122 " Got this from the '%s' variable." % self.parent_name.token
123 )
124 raise TemplateSyntaxError(error_msg)
125 if isinstance(parent, Template):
126 # parent is a django.template.Template
127 return parent
128 if isinstance(getattr(parent, "template", None), Template):
129 # parent is a django.template.backends.django.Template
130 return parent.template
131 return self.find_template(parent, context)
132
133 def render(self, context):
134 compiled_parent = self.get_parent(context)
135
136 if BLOCK_CONTEXT_KEY not in context.render_context:
137 context.render_context[BLOCK_CONTEXT_KEY] = BlockContext()
138 block_context = context.render_context[BLOCK_CONTEXT_KEY]
139
140 # Add the block nodes from this node to the block context
141 block_context.add_blocks(self.blocks)
142
143 # If this block's parent doesn't have an extends node it is the root,
144 # and its block nodes also need to be added to the block context.
145 for node in compiled_parent.nodelist:
146 # The ExtendsNode has to be the first non-text node.
147 if not isinstance(node, TextNode):
148 if not isinstance(node, ExtendsNode):
149 blocks = {
150 n.name: n
151 for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode)
152 }
153 block_context.add_blocks(blocks)
154 break
155
156 # Call Template._render explicitly so the parser context stays
157 # the same.
158 with context.render_context.push_state(compiled_parent, isolated_context=False):
159 return compiled_parent._render(context)
160
161
162 class IncludeNode(Node):
163 context_key = "__include_context"
164
165 def __init__(
166 self, template, *args, extra_context=None, isolated_context=False, **kwargs
167 ):
168 self.template = template
169 self.extra_context = extra_context or {}
170 self.isolated_context = isolated_context
171 super().__init__(*args, **kwargs)
172
173 def __repr__(self):
174 return f"<{self.__class__.__qualname__}: template={self.template!r}>"
175
176 def render(self, context):
177 """
178 Render the specified template and context. Cache the template object
179 in render_context to avoid reparsing and loading when used in a for
180 loop.
181 """
182 template = self.template.resolve(context)
183 # Does this quack like a Template?
184 if not callable(getattr(template, "render", None)):
185 # If not, try the cache and select_template().
186 template_name = template or ()
187 if isinstance(template_name, str):
188 template_name = (
189 construct_relative_path(
190 self.origin.template_name,
191 template_name,
192 ),
193 )
194 else:
195 template_name = tuple(template_name)
196 cache = context.render_context.dicts[0].setdefault(self, {})
197 template = cache.get(template_name)
198 if template is None:
199 template = context.template.engine.select_template(template_name)
200 cache[template_name] = template
201 # Use the base.Template of a backends.django.Template.
202 elif hasattr(template, "template"):
203 template = template.template
204 values = {
205 name: var.resolve(context) for name, var in self.extra_context.items()
206 }
207 if self.isolated_context:
208 return template.render(context.new(values))
209 with context.push(**values):
210 return template.render(context)
211
212
213 @register.tag("block")
214 def do_block(parser, token):
215 """
216 Define a block that can be overridden by child templates.
217 """
218 # token.split_contents() isn't useful here because this tag doesn't accept
219 # variable as arguments.
220 bits = token.contents.split()
221 if len(bits) != 2:
222 raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0])
223 block_name = bits[1]
224 # Keep track of the names of BlockNodes found in this template, so we can
225 # check for duplication.
226 try:
227 if block_name in parser.__loaded_blocks:
228 raise TemplateSyntaxError(
229 "'%s' tag with name '%s' appears more than once" % (bits[0], block_name)
230 )
231 parser.__loaded_blocks.append(block_name)
232 except AttributeError: # parser.__loaded_blocks isn't a list yet
233 parser.__loaded_blocks = [block_name]
234 nodelist = parser.parse(("endblock",))
235
236 # This check is kept for backwards-compatibility. See #3100.
237 endblock = parser.next_token()
238 acceptable_endblocks = ("endblock", "endblock %s" % block_name)
239 if endblock.contents not in acceptable_endblocks:
240 parser.invalid_block_tag(endblock, "endblock", acceptable_endblocks)
241
242 return BlockNode(block_name, nodelist)
243
244
245 def construct_relative_path(
246 current_template_name,
247 relative_name,
248 allow_recursion=False,
249 ):
250 """
251 Convert a relative path (starting with './' or '../') to the full template
252 name based on the current_template_name.
253 """
254 new_name = relative_name.strip("'\"")
255 if not new_name.startswith(("./", "../")):
256 # relative_name is a variable or a literal that doesn't contain a
257 # relative path.
258 return relative_name
259
260 new_name = posixpath.normpath(
261 posixpath.join(
262 posixpath.dirname(current_template_name.lstrip("/")),
263 new_name,
264 )
265 )
266 if new_name.startswith("../"):
267 raise TemplateSyntaxError(
268 "The relative path '%s' points outside the file hierarchy that "
269 "template '%s' is in." % (relative_name, current_template_name)
270 )
271 if not allow_recursion and current_template_name.lstrip("/") == new_name:
272 raise TemplateSyntaxError(
273 "The relative path '%s' was translated to template name '%s', the "
274 "same template in which the tag appears."
275 % (relative_name, current_template_name)
276 )
277 has_quotes = (
278 relative_name.startswith(('"', "'")) and relative_name[0] == relative_name[-1]
279 )
280 return f'"{new_name}"' if has_quotes else new_name
281
282
283 @register.tag("extends")
284 def do_extends(parser, token):
285 """
286 Signal that this template extends a parent template.
287
288 This tag may be used in two ways: ``{% extends "base" %}`` (with quotes)
289 uses the literal value "base" as the name of the parent template to extend,
290 or ``{% extends variable %}`` uses the value of ``variable`` as either the
291 name of the parent template to extend (if it evaluates to a string) or as
292 the parent template itself (if it evaluates to a Template object).
293 """
294 bits = token.split_contents()
295 if len(bits) != 2:
296 raise TemplateSyntaxError("'%s' takes one argument" % bits[0])
297 bits[1] = construct_relative_path(parser.origin.template_name, bits[1])
298 parent_name = parser.compile_filter(bits[1])
299 nodelist = parser.parse()
300 if nodelist.get_nodes_by_type(ExtendsNode):
301 raise TemplateSyntaxError(
302 "'%s' cannot appear more than once in the same template" % bits[0]
303 )
304 return ExtendsNode(nodelist, parent_name)
305
306
307 @register.tag("include")
308 def do_include(parser, token):
309 """
310 Load a template and render it with the current context. You can pass
311 additional context using keyword arguments.
312
313 Example::
314
315 {% include "foo/some_include" %}
316 {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %}
317
318 Use the ``only`` argument to exclude the current context when rendering
319 the included template::
320
321 {% include "foo/some_include" only %}
322 {% include "foo/some_include" with bar="1" only %}
323 """
324 bits = token.split_contents()
325 if len(bits) < 2:
326 raise TemplateSyntaxError(
327 "%r tag takes at least one argument: the name of the template to "
328 "be included." % bits[0]
329 )
330 options = {}
331 remaining_bits = bits[2:]
332 while remaining_bits:
333 option = remaining_bits.pop(0)
334 if option in options:
335 raise TemplateSyntaxError(
336 "The %r option was specified more than once." % option
337 )
338 if option == "with":
339 value = token_kwargs(remaining_bits, parser, support_legacy=False)
340 if not value:
341 raise TemplateSyntaxError(
342 '"with" in %r tag needs at least one keyword argument.' % bits[0]
343 )
344 elif option == "only":
345 value = True
346 else:
347 raise TemplateSyntaxError(
348 "Unknown argument for %r tag: %r." % (bits[0], option)
349 )
350 options[option] = value
351 isolated_context = options.get("only", False)
352 namemap = options.get("with", {})
353 bits[1] = construct_relative_path(
354 parser.origin.template_name,
355 bits[1],
356 allow_recursion=True,
357 )
358 return IncludeNode(
359 parser.compile_filter(bits[1]),
360 extra_context=namemap,
361 isolated_context=isolated_context,
362 )