from django import template
register = template.Library()
@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," %}
"""
(attribute, default) = args.split(',')
try:
return obj.__getattribute__(attribute)
except AttributeError:
return obj.__dict__.get(attribute, default)
except:
return default
Comments
I needed to pass the attribute name as a variable, not a string. So, to make this kind of usage work:
I replaced line 14 with:
I actually wrote my own filter to do this. Then, when I came to post it, I found that this one existed and included a nifty default value. I decided to merge them.
WRoks for me.
#