From 496dbed960f5f5821326c550debc368a14f52c95 Mon Sep 17 00:00:00 2001 From: sametmax Date: Sun, 14 Oct 2012 21:09:27 +0200 Subject: [PATCH] Adding a getattr template tag --- django_quicky/templatetags/__init__.py | 4 ++ django_quicky/templatetags/introspection.py | 43 +++++++++++++++++++++ 2 files changed, 47 insertions(+) create mode 100644 django_quicky/templatetags/__init__.py create mode 100755 django_quicky/templatetags/introspection.py diff --git a/django_quicky/templatetags/__init__.py b/django_quicky/templatetags/__init__.py new file mode 100644 index 0000000..00d8466 --- /dev/null +++ b/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 + diff --git a/django_quicky/templatetags/introspection.py b/django_quicky/templatetags/introspection.py new file mode 100755 index 0000000..2ce4145 --- /dev/null +++ b/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 \ No newline at end of file