PageRenderTime 428ms CodeModel.GetById 211ms app.highlight 4ms RepoModel.GetById 157ms app.codeStats 1ms

/smileys/templatetags/smiley_tags.py

https://code.google.com/p/django-smileys/
Python | 39 lines | 17 code | 7 blank | 15 comment | 4 complexity | 8a9aedf88ae48deb57d1f080986d0933 MD5 | raw file
 1from django import template
 2from smileys.models import Smiley
 3import re
 4
 5register = template.Library()
 6
 7def gen_smileys(value, type):
 8    """
 9    Replaces all occurrences of the active smiley patterns in `value` with a
10    tag that points to the image associated with the respective pattern.
11
12    Hoorah!
13    """
14
15    for smiley in Smiley.objects.filter(is_active=True):
16        # come up with the <img> tag
17        if type == 'html':
18            img = '<img class="smiley" src="%s" alt="%s" height="%i" width="%i" />' % (smiley.image.url, smiley.description, smiley.image.height, smiley.image.width)
19        elif type == 'textile':
20            # the description between parentheses is told not to be parsed by
21            # textile with the '==' textile tag surrounding it. the parentheses
22            # are separated from '==' so that it does not clash with a smiley
23            # like =)
24
25            img = '!%s ( == %s == )!' % (smiley.image.url, smiley.description)
26
27        if smiley.is_regex:
28            # regex patterns allow you to use the same Smiley for multiple
29            # ways to type a smiley
30            value = re.sub(smiley.pattern, img, value)
31        else:
32            # this is the stupid (strict) way
33            value = value.replace(smiley.pattern, img)
34
35    return value
36
37# register the filters
38register.filter('smileys', lambda v: gen_smileys(v, 'html'))
39register.filter('textile_smileys', lambda v: gen_smileys(v, 'textile'))