Login

icon shortcut - pseudohtml tag with attribute merging and variables resolving

Author:
wiz
Posted:
June 2, 2010
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

A shortcut for generating img-s with predefined classes and attributes that mimics a html tag, while resolving context variables inside {% %} without crutches like tag/stuff/endtag.

Used as {% icon test class="spam" eggs="{{ object.pk }}" %} yields <img src="http://host.tld/media/icons/test.png" alt="" class="icon16 spam" eggs="42"/>.

Not customizable here for simplicity.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.