from django.conf import settings
from django import template
register = template.Library()
re_attrs = template.re.compile('(\w+)="(.*?)"')
class IconNode(template.Node):
def __init__(self, icon, nodelist):
self.icon = icon
self.nodelist = nodelist
self.attrs = {"src": "%sicons/%s.png" % (settings.MEDIA_URL, self.icon),
"class": "icon16", "alt": ""}
def render(self, context):
attrs = self.attrs.copy()
for key, value in re_attrs.findall(self.nodelist.render(context)):
if key in attrs:
attrs[key] = "%s %s" % (attrs[key], value)
else:
attrs[key] = value
return u'<img %s/>' % " ".join('%s="%s"' % attr for attr in attrs.iteritems())
@register.tag("icon")
def parse_icon(parser, token):
parts = token.contents.strip().split(None, 2)
return IconNode(parts[1], template.Template(parts[2]).nodelist)
Comments
Writing python templatetags files for each macro is painful. Try django-containers and you wouldn't need python code, but only simple html file!
#