Login

improved getattr template filter

Author:
luckystarr
Posted:
September 11, 2007
Language:
Python
Version:
.96
Tags:
template filter get attr
Score:
0 (after 0 ratings)

I tried to use Joshua's nice and very useful getattr template filter (#38), but ran into a few problems.

I used it on objects outside of my control (admin internals, coughcough) and on some of them the code didn't catch the resulting exceptions. So I improved the error handling a bit.

Furthermore, the code now also returns the value of a callable instead of the callable itself (last 4 lines).

Looking at my code though, it can certainly be improved further.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@register.filter
def getattr (obj, args):
    """ Try to get an attribute from an object.

    Example: {% if block|getattr:"editable,True" %}

    Beware that the default is always a string, if you want this
    to return False, pass an empty second argument:
    {% if block|getattr:"editable," %}
    """
    splitargs = args.split(',')
    try:
      (attribute, default) = splitargs
    except ValueError:
      (attribute, default) = args, ''

    try:
      attr = obj.__getattribute__(attribute)
    except AttributeError:
      attr = obj.__dict__.get(attribute, default)
    except:
      attr = default

    if hasattr(attr, '__call__'):
        return attr.__call__()
    else:
        return attr

More like this

Comments

Please login first before commenting.