Skip to content

Commit

Permalink
Adding a getattr template tag
Browse files Browse the repository at this point in the history
  • Loading branch information
sametmax committed Oct 14, 2012
1 parent 5242249 commit 496dbed
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
4 changes: 4 additions & 0 deletions django_quicky/templatetags/__init__.py
@@ -0,0 +1,4 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu

43 changes: 43 additions & 0 deletions django_quicky/templatetags/introspection.py
@@ -0,0 +1,43 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu

"""
Tag to use python introspection in a Django template
"""

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," %}
Source: http://djangosnippets.org/snippets/38/
"""
try:
args = args.split(',')
except AttributeError:
raise AttributeError(('"%s" is not a proper value the "getattr" '
'filter applied to "%s"') % (args, obj))

if len(args) == 1:
(attribute, default) = [args[0], '']
else:
(attribute, default) = args

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

0 comments on commit 496dbed

Please sign in to comment.