Code

Ticket #2016: 0002-Adds-the-object_tag-decorator.diff

File 0002-Adds-the-object_tag-decorator.diff, 1.7 KB (added by marcusf, 5 years ago)
Line 
1diff --git a/django/template/__init__.py b/django/template/__init__.py
2index 14eea5c..03e2a6c 100644
3--- a/django/template/__init__.py
4+++ b/django/template/__init__.py
5@@ -916,6 +916,38 @@ class Library(object):
6         self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
7         return func
8 
9+    def object_tag(self, func):
10+        params, xx, xxx, defaults = getargspec(func)
11+
12+        class ObjectNode(Node):
13+            def __init__(self, vars_to_resolve, var_name):
14+                self.vars_to_resolve = map(Variable, vars_to_resolve)
15+                self.var_name = var_name
16+
17+            def render(self, context):
18+                resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]
19+                obj = func(*resolved_vars)
20+                context[self.var_name] = obj
21+                return ''
22+
23+        def object_tag_compiler(params, defaults, name, node_class, parser, token):
24+            bits = token.split_contents()[1:]
25+
26+            if len(bits) < 2 or bits[-2] != 'as':
27+                raise TemplateSyntaxError("the next to last argument to %s must be 'as'" % name)
28+
29+            var_name, bits = bits[-1], bits[:-2]
30+            match_number_of_arguments(bits, params, defaults, name)
31+
32+            return node_class(bits, var_name)
33+
34+        compile_func = curry(object_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, ObjectNode)
35+        compile_func.__doc__ = func.__doc__
36+
37+        self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
38+
39+        return func
40+
41     def inclusion_tag(self, file_name, context_class=Context, takes_context=False):
42         def dec(func):
43             params, xx, xxx, defaults = getargspec(func)