/smileys/templatetags/smiley_tags.py

https://code.google.com/p/django-smileys/ · Python · 39 lines · 17 code · 7 blank · 15 comment · 5 complexity · 8a9aedf88ae48deb57d1f080986d0933 MD5 · raw file

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