Performing a getattr() style lookup in a django template


Question

Python's getattr() method is useful when you don't know the name of a certain attribute in advance.

This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups?

1
42
5/10/2009 5:15:16 AM

Accepted Answer

I also had to write this code as a custom template tag recently. To handle all look-up scenarios, it first does a standard attribute look-up, then tries to do a dictionary look-up, then tries a getitem lookup (for lists to work), then follows standard Django template behavior when an object is not found.

(updated 2009-08-26 to now handle list index lookups as well)

# app/templatetags/getattribute.py

import re
from django import template
from django.conf import settings

numeric_test = re.compile("^\d+$")
register = template.Library()

def getattribute(value, arg):
    """Gets an attribute of an object dynamically from a string name"""

    if hasattr(value, str(arg)):
        return getattr(value, arg)
    elif hasattr(value, 'has_key') and value.has_key(arg):
        return value[arg]
    elif numeric_test.match(str(arg)) and len(value) > int(arg):
        return value[int(arg)]
    else:
        return settings.TEMPLATE_STRING_IF_INVALID

register.filter('getattribute', getattribute)

Template usage:

{% load getattribute %}
{{ object|getattribute:dynamic_string_var }}


57
4/26/2018 11:39:44 PM

Keeping the distinction between get and getattr,

@register.filter(name='get')
def get(o, index):
    try:
        return o[index]
    except:
        return settings.TEMPLATE_STRING_IF_INVALID


@register.filter(name='getattr')
def getattrfilter(o, attr):
    try:
        return getattr(o, attr)
    except:
        return settings.TEMPLATE_STRING_IF_INVALID

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon