Ticket #2016: object_tag.patch

File object_tag.patch, 1.7 KB (added by jason@…, 18 years ago)
  • django/template/__init__.py

     
    834834        self.tag(func.__name__, compile_func)
    835835        return func
    836836
     837    def object_tag(self, func):
     838        """
     839        Makes it easier to write template tags that load objects into the template.
     840        These tags are of the form (tag) [args] as (varname)
     841        For example: get_some_articles 5 as recent_articles
     842       
     843        object_tag should be used to decorate a function that takes [args] as its
     844        parameters and returns the object to be assigned to (varname) in the template.
     845        For example:
     846        @register.object_tag
     847        def get_some_articles(num):
     848            return MyArticleModel.objects.all()[:num]
     849        """
     850        def compile_func(parser, token):
     851            bits = token.contents.split(None)
     852            tagname, bits = bits[0], bits[1:]
     853            if len(bits) < 2 or bits[-2] != "as":
     854                raise TemplateSyntaxError, "Tag must be of format %s [args] as (varname)" % tagname
     855            args, varname = bits[:-2], bits[-1]
     856           
     857            class ObjectTagNode(Node):
     858                def render(self, context):
     859                    context[varname] = func(*args)
     860                    return ''
     861           
     862            return ObjectTagNode()
     863       
     864        compile_func.__doc__ = func.__doc__
     865        self.tag(func.__name__, compile_func)
     866        return func
     867
    837868    def inclusion_tag(self, file_name, context_class=Context, takes_context=False):
    838869        def dec(func):
    839870            (params, xx, xxx, defaults) = getargspec(func)
Back to Top