One of things I had the hardest time finding was a good example of Template Tags in Django; so here is my basic template tags file I add to every new project (GPLv2). A lot of people have their own, and I’m sure in the future I’ll add on to my basics; but for now these get me by. One of the things I’ve been wanting to do is write a good small primer for beginning Django, consider this my first foray in to making that a reality.
from django import template
from django.template import Variable, VariableDoesNotExist
register = template.Library()
@register.filter
def gVal(object, attr):
"""Check the array, dict, etc for a value"""
quasai = { 'object' : object }
#print "gVal :: " + str(attr) +" - "+ str(quasai)
try:
value = Variable('object.%s' % attr).resolve(quasai)
except VariableDoesNotExist:
value = None
return value
@register.filter
def xVal(a,b):
"""Since Python resolves left to right in template tags: pass value and then the dick to check; returns value or 0"""
#print "xVal",a,b
if b.has_key(a):
value = b[a]
else:
value = "0"
return value
@register.filter
def hexVert(value):
"""Removes all values of # from the given string and replaces with %23"""
if value != None:
value = value.replace("#", '%23')
value = value.replace("!", '%21')
value = value.replace("&", '%26')
return value
Leave a Reply