Code

Opened 9 years ago

Closed 8 years ago

Last modified 8 years ago

#577 closed enhancement (wontfix)

Dynamic attribute lookup in templates

Reported by: wojtek3@… Owned by: adrian
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: UI/UX:

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)

Attachments (0)

Change History (4)

comment:1 Changed 9 years ago by anonymous

  • Type changed from defect to enhancement

comment:2 Changed 9 years ago by adrian

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 Changed 8 years ago by rjwittams

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

comment:4 Changed 8 years ago by rjwittams

  • Resolution set to wontfix
  • Status changed from new to closed

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.