icon shortcut - pseudohtml tag with attribute merging and variables resolving

 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. Boolean Image Flag TemplateTag by MichaelAnckaert 5 years, 4 months ago
  2. Dynamic Regroup Template Tag by btaylordesign 2 years, 8 months ago
  3. Variable resolving URL template tag by UloPe 5 years, 1 month ago
  4. Silk icon tags by Hangya 3 years, 7 months ago
  5. ImageField for admin with thumbnail by semente 4 years, 10 months ago

Comments

(Forgotten your password?)