Debian Codegraph @

django/template/library.py

raw
1 from collections.abc import Iterable
2 from functools import wraps
3 from importlib import import_module
4 from inspect import getfullargspec, unwrap
5
6 from django.utils.html import conditional_escape
7 from django.utils.inspect import lazy_annotations
8
9 from .base import Node, Template, token_kwargs
10 from .exceptions import TemplateSyntaxError
11
12
13 class InvalidTemplateLibrary(Exception):
14 pass
15
16
17 class Library:
18 """
19 A class for registering template tags and filters. Compiled filter and
20 template tag functions are stored in the filters and tags attributes.
21 The filter, simple_tag, and inclusion_tag methods provide a convenient
22 way to register callables as tags.
23 """
24
25 def __init__(self):
26 self.filters = {}
27 self.tags = {}
28
29 def tag(self, name=None, compile_function=None):
30 if name is None and compile_function is None:
31 # @register.tag()
32 return self.tag_function
33 elif name is not None and compile_function is None:
34 if callable(name):
35 # @register.tag
36 return self.tag_function(name)
37 else:
38 # @register.tag('somename') or @register.tag(name='somename')
39 def dec(func):
40 return self.tag(name, func)
41
42 return dec
43 elif name is not None and compile_function is not None:
44 # register.tag('somename', somefunc)
45 self.tags[name] = compile_function
46 return compile_function
47 else:
48 raise ValueError(
49 "Unsupported arguments to Library.tag: (%r, %r)"
50 % (name, compile_function),
51 )
52
53 def tag_function(self, func):
54 self.tags[func.__name__] = func
55 return func
56
57 def filter(self, name=None, filter_func=None, **flags):
58 """
59 Register a callable as a template filter. Example:
60
61 @register.filter
62 def lower(value):
63 return value.lower()
64 """
65 if name is None and filter_func is None:
66 # @register.filter()
67 def dec(func):
68 return self.filter_function(func, **flags)
69
70 return dec
71 elif name is not None and filter_func is None:
72 if callable(name):
73 # @register.filter
74 return self.filter_function(name, **flags)
75 else:
76 # @register.filter('somename') or @register.filter(name='somename')
77 def dec(func):
78 return self.filter(name, func, **flags)
79
80 return dec
81 elif name is not None and filter_func is not None:
82 # register.filter('somename', somefunc)
83 self.filters[name] = filter_func
84 for attr in ("expects_localtime", "is_safe", "needs_autoescape"):
85 if attr in flags:
86 value = flags[attr]
87 # set the flag on the filter for FilterExpression.resolve
88 setattr(filter_func, attr, value)
89 # set the flag on the innermost decorated function
90 # for decorators that need it, e.g. stringfilter
91 setattr(unwrap(filter_func), attr, value)
92 filter_func._filter_name = name
93 return filter_func
94 else:
95 raise ValueError(
96 "Unsupported arguments to Library.filter: (%r, %r)"
97 % (name, filter_func),
98 )
99
100 def filter_function(self, func, **flags):
101 return self.filter(func.__name__, func, **flags)
102
103 def simple_tag(self, func=None, takes_context=None, name=None):
104 """
105 Register a callable as a compiled template tag. Example:
106
107 @register.simple_tag
108 def hello(*args, **kwargs):
109 return 'world'
110 """
111
112 def dec(func):
113 with lazy_annotations():
114 (
115 params,
116 varargs,
117 varkw,
118 defaults,
119 kwonly,
120 kwonly_defaults,
121 _,
122 ) = getfullargspec(unwrap(func))
123 function_name = name or func.__name__
124
125 @wraps(func)
126 def compile_func(parser, token):
127 bits = token.split_contents()[1:]
128 target_var = None
129 if len(bits) >= 2 and bits[-2] == "as":
130 target_var = bits[-1]
131 bits = bits[:-2]
132 args, kwargs = parse_bits(
133 parser,
134 bits,
135 params,
136 varargs,
137 varkw,
138 defaults,
139 kwonly,
140 kwonly_defaults,
141 takes_context,
142 function_name,
143 )
144 return SimpleNode(func, takes_context, args, kwargs, target_var)
145
146 self.tag(function_name, compile_func)
147 return func
148
149 if func is None:
150 # @register.simple_tag(...)
151 return dec
152 elif callable(func):
153 # @register.simple_tag
154 return dec(func)
155 else:
156 raise ValueError("Invalid arguments provided to simple_tag")
157
158 def simple_block_tag(self, func=None, takes_context=None, name=None, end_name=None):
159 """
160 Register a callable as a compiled block template tag. Example:
161
162 @register.simple_block_tag
163 def hello(content):
164 return 'world'
165 """
166
167 def dec(func):
168 nonlocal end_name
169 with lazy_annotations():
170 (
171 params,
172 varargs,
173 varkw,
174 defaults,
175 kwonly,
176 kwonly_defaults,
177 _,
178 ) = getfullargspec(unwrap(func))
179 function_name = name or func.__name__
180
181 if end_name is None:
182 end_name = f"end{function_name}"
183
184 @wraps(func)
185 def compile_func(parser, token):
186 tag_params = params.copy()
187
188 if takes_context:
189 if len(tag_params) >= 2 and tag_params[1] == "content":
190 del tag_params[1]
191 else:
192 raise TemplateSyntaxError(
193 f"{function_name!r} is decorated with takes_context=True so"
194 " it must have a first argument of 'context' and a second "
195 "argument of 'content'"
196 )
197 elif tag_params and tag_params[0] == "content":
198 del tag_params[0]
199 else:
200 raise TemplateSyntaxError(
201 f"'{function_name}' must have a first argument of 'content'"
202 )
203
204 bits = token.split_contents()[1:]
205 target_var = None
206 if len(bits) >= 2 and bits[-2] == "as":
207 target_var = bits[-1]
208 bits = bits[:-2]
209
210 nodelist = parser.parse((end_name,))
211 parser.delete_first_token()
212
213 args, kwargs = parse_bits(
214 parser,
215 bits,
216 tag_params,
217 varargs,
218 varkw,
219 defaults,
220 kwonly,
221 kwonly_defaults,
222 takes_context,
223 function_name,
224 )
225
226 return SimpleBlockNode(
227 nodelist, func, takes_context, args, kwargs, target_var
228 )
229
230 self.tag(function_name, compile_func)
231 return func
232
233 if func is None:
234 # @register.simple_block_tag(...)
235 return dec
236 elif callable(func):
237 # @register.simple_block_tag
238 return dec(func)
239 else:
240 raise ValueError("Invalid arguments provided to simple_block_tag")
241
242 def inclusion_tag(self, filename, func=None, takes_context=None, name=None):
243 """
244 Register a callable as an inclusion tag:
245
246 @register.inclusion_tag('results.html')
247 def show_results(poll):
248 choices = poll.choice_set.all()
249 return {'choices': choices}
250 """
251
252 def dec(func):
253 with lazy_annotations():
254 (
255 params,
256 varargs,
257 varkw,
258 defaults,
259 kwonly,
260 kwonly_defaults,
261 _,
262 ) = getfullargspec(unwrap(func))
263 function_name = name or func.__name__
264
265 @wraps(func)
266 def compile_func(parser, token):
267 bits = token.split_contents()[1:]
268 args, kwargs = parse_bits(
269 parser,
270 bits,
271 params,
272 varargs,
273 varkw,
274 defaults,
275 kwonly,
276 kwonly_defaults,
277 takes_context,
278 function_name,
279 )
280 return InclusionNode(
281 func,
282 takes_context,
283 args,
284 kwargs,
285 filename,
286 )
287
288 self.tag(function_name, compile_func)
289 return func
290
291 return dec
292
293
294 class TagHelperNode(Node):
295 """
296 Base class for tag helper nodes such as SimpleNode and InclusionNode.
297 Manages the positional and keyword arguments to be passed to the decorated
298 function.
299 """
300
301 def __init__(self, func, takes_context, args, kwargs):
302 self.func = func
303 self.takes_context = takes_context
304 self.args = args
305 self.kwargs = kwargs
306
307 def get_resolved_arguments(self, context):
308 resolved_args = [var.resolve(context) for var in self.args]
309 if self.takes_context:
310 resolved_args = [context] + resolved_args
311 resolved_kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()}
312 return resolved_args, resolved_kwargs
313
314
315 class SimpleNode(TagHelperNode):
316 child_nodelists = ()
317
318 def __init__(self, func, takes_context, args, kwargs, target_var):
319 super().__init__(func, takes_context, args, kwargs)
320 self.target_var = target_var
321
322 def render(self, context):
323 resolved_args, resolved_kwargs = self.get_resolved_arguments(context)
324 output = self.func(*resolved_args, **resolved_kwargs)
325 if self.target_var is not None:
326 context[self.target_var] = output
327 return ""
328 if context.autoescape:
329 output = conditional_escape(output)
330 return output
331
332
333 class SimpleBlockNode(SimpleNode):
334 def __init__(self, nodelist, *args, **kwargs):
335 super().__init__(*args, **kwargs)
336 self.nodelist = nodelist
337
338 def get_resolved_arguments(self, context):
339 resolved_args, resolved_kwargs = super().get_resolved_arguments(context)
340
341 # Restore the "content" argument.
342 # It will move depending on whether takes_context was passed.
343 resolved_args.insert(
344 1 if self.takes_context else 0, self.nodelist.render(context)
345 )
346
347 return resolved_args, resolved_kwargs
348
349
350 class InclusionNode(TagHelperNode):
351 def __init__(self, func, takes_context, args, kwargs, filename):
352 super().__init__(func, takes_context, args, kwargs)
353 self.filename = filename
354
355 def render(self, context):
356 """
357 Render the specified template and context. Cache the template object
358 in render_context to avoid reparsing and loading when used in a for
359 loop.
360 """
361 resolved_args, resolved_kwargs = self.get_resolved_arguments(context)
362 _dict = self.func(*resolved_args, **resolved_kwargs)
363
364 t = context.render_context.get(self)
365 if t is None:
366 if isinstance(self.filename, Template):
367 t = self.filename
368 elif isinstance(getattr(self.filename, "template", None), Template):
369 t = self.filename.template
370 elif not isinstance(self.filename, str) and isinstance(
371 self.filename, Iterable
372 ):
373 t = context.template.engine.select_template(self.filename)
374 else:
375 t = context.template.engine.get_template(self.filename)
376 context.render_context[self] = t
377 new_context = context.new(_dict)
378 # Copy across the CSRF token, if present, because inclusion tags are
379 # often used for forms, and we need instructions for using CSRF
380 # protection to be as simple as possible.
381 csrf_token = context.get("csrf_token")
382 if csrf_token is not None:
383 new_context["csrf_token"] = csrf_token
384 return t.render(new_context)
385
386
387 def parse_bits(
388 parser,
389 bits,
390 params,
391 varargs,
392 varkw,
393 defaults,
394 kwonly,
395 kwonly_defaults,
396 takes_context,
397 name,
398 ):
399 """
400 Parse bits for template tag helpers simple_tag and inclusion_tag, in
401 particular by detecting syntax errors and by extracting positional and
402 keyword arguments.
403 """
404 if takes_context:
405 if params and params[0] == "context":
406 params = params[1:]
407 else:
408 raise TemplateSyntaxError(
409 "'%s' is decorated with takes_context=True so it must "
410 "have a first argument of 'context'" % name
411 )
412 args = []
413 kwargs = {}
414 unhandled_params = list(params)
415 unhandled_kwargs = [
416 kwarg for kwarg in kwonly if not kwonly_defaults or kwarg not in kwonly_defaults
417 ]
418 for bit in bits:
419 # First we try to extract a potential kwarg from the bit
420 kwarg = token_kwargs([bit], parser)
421 if kwarg:
422 # The kwarg was successfully extracted
423 param, value = kwarg.popitem()
424 if param not in params and param not in kwonly and varkw is None:
425 # An unexpected keyword argument was supplied
426 raise TemplateSyntaxError(
427 "'%s' received unexpected keyword argument '%s'" % (name, param)
428 )
429 elif param in kwargs:
430 # The keyword argument has already been supplied once
431 raise TemplateSyntaxError(
432 "'%s' received multiple values for keyword argument '%s'"
433 % (name, param)
434 )
435 else:
436 # All good, record the keyword argument
437 kwargs[str(param)] = value
438 if param in unhandled_params:
439 # If using the keyword syntax for a positional arg, then
440 # consume it.
441 unhandled_params.remove(param)
442 elif param in unhandled_kwargs:
443 # Same for keyword-only arguments
444 unhandled_kwargs.remove(param)
445 else:
446 if kwargs:
447 raise TemplateSyntaxError(
448 "'%s' received some positional argument(s) after some "
449 "keyword argument(s)" % name
450 )
451 else:
452 # Record the positional argument
453 args.append(parser.compile_filter(bit))
454 try:
455 # Consume from the list of expected positional arguments
456 unhandled_params.pop(0)
457 except IndexError:
458 if varargs is None:
459 raise TemplateSyntaxError(
460 "'%s' received too many positional arguments" % name
461 )
462 if defaults is not None:
463 # Consider the last n params handled, where n is the
464 # number of defaults.
465 unhandled_params = unhandled_params[: -len(defaults)]
466 if unhandled_params or unhandled_kwargs:
467 # Some positional arguments were not supplied
468 raise TemplateSyntaxError(
469 "'%s' did not receive value(s) for the argument(s): %s"
470 % (name, ", ".join("'%s'" % p for p in unhandled_params + unhandled_kwargs))
471 )
472 return args, kwargs
473
474
475 def import_library(name):
476 """
477 Load a Library object from a template tag module.
478 """
479 try:
480 module = import_module(name)
481 except ImportError as e:
482 raise InvalidTemplateLibrary(
483 "Invalid template library specified. ImportError raised when "
484 "trying to load '%s': %s" % (name, e)
485 )
486 try:
487 return module.register
488 except AttributeError:
489 raise InvalidTemplateLibrary(
490 "Module %s does not have a variable named 'register'" % name,
491 )