Opened 19 years ago

Closed 19 years ago

Last modified 18 years ago

#577 closed enhancement (wontfix)

Dynamic attribute lookup in templates

Reported by: wojtek3@… Owned by: Adrian Holovaty
Component: Template system Version:
Severity: normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I've written a tag for dynamic attribute lookup in templates. I bet it's useful for many Django users so here it is, hopefuly it will be included in the base code :)

class GetattrNode(Node):
    def __init__(self, vars):
        self.vars = vars

    def render(self, context):
        return str(resolve_variable("%s.%s" % (self.vars[0], resolve_variable(self.vars[1], context)), context))

def do_getattr(parser, token):    
    """
    Return the value of the given attribute in the given object.

    This differs from the regular use of {{ object.attribute }}.  In the case of {% get object attr_var %}
    attr_var is a variable and the actual attribute fetched from 'object' is the value of that var not
    it's name like in regular Django variable resolution.
    """
    bits = token.contents.split()
    if len(bits) != 3:
        raise TemplateSyntaxError, "usage: getattr <object> <attribute>"
    return GetattrNode(bits[1:])

register_tag('getattr', do_getattr)

Change History (4)

comment:1 by anonymous, 19 years ago

Type: defectenhancement

comment:2 by Adrian Holovaty, 19 years ago

It's a good addition, but because it's more of a "power user" feature, I think a separate template-tag library (in django.contrib) would be a better place for it than in the default tag library. Does introspection.py sound like a decent name for that external tag library?

comment:3 by rjwittams, 19 years ago

This is covered by the lookup filter in #959. Closing this in favour of that, as it is a lot more flexible.

comment:4 by rjwittams, 19 years ago

Resolution: wontfix
Status: newclosed
Note: See TracTickets for help on using tickets.
Back to Top