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

File 0002-Adds-the-object_tag-decorator.diff, 1.7 KB (added by marcusf, 6 years ago)
  • django/template/__init__.py

    diff --git a/django/template/__init__.py b/django/template/__init__.py
    index 14eea5c..03e2a6c 100644
    a b class Library(object): 
    916916        self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
    917917        return func
    918918
     919    def object_tag(self, func):
     920        params, xx, xxx, defaults = getargspec(func)
     921
     922        class ObjectNode(Node):
     923            def __init__(self, vars_to_resolve, var_name):
     924                self.vars_to_resolve = map(Variable, vars_to_resolve)
     925                self.var_name = var_name
     926
     927            def render(self, context):
     928                resolved_vars = [var.resolve(context) for var in self.vars_to_resolve]
     929                obj = func(*resolved_vars)
     930                context[self.var_name] = obj
     931                return ''
     932
     933        def object_tag_compiler(params, defaults, name, node_class, parser, token):
     934            bits = token.split_contents()[1:]
     935
     936            if len(bits) < 2 or bits[-2] != 'as':
     937                raise TemplateSyntaxError("the next to last argument to %s must be 'as'" % name)
     938
     939            var_name, bits = bits[-1], bits[:-2]
     940            match_number_of_arguments(bits, params, defaults, name)
     941
     942            return node_class(bits, var_name)
     943
     944        compile_func = curry(object_tag_compiler, params, defaults, getattr(func, "_decorated_function", func).__name__, ObjectNode)
     945        compile_func.__doc__ = func.__doc__
     946
     947        self.tag(getattr(func, "_decorated_function", func).__name__, compile_func)
     948
     949        return func
     950
    919951    def inclusion_tag(self, file_name, context_class=Context, takes_context=False):
    920952        def dec(func):
    921953            params, xx, xxx, defaults = getargspec(func)
Back to Top