Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
#!/usr/bin/env python | ||
# -*- coding: utf-8 -*- | ||
# vim: ai ts=4 sts=4 et sw=4 nu | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |