annotate gpp/smiley/__init__.py @ 124:9c18250972d5

Refactored the markdown/smiley logic. Created classes for Markdown and Smilify. No longer call render_to_string() in models.py for various models.
author Brian Neal <bgneal@gmail.com>
date Sat, 14 Nov 2009 04:32:32 +0000
parents dbd703f7d63a
children 48621ba5c385
rev   line source
bgneal@124 1 """
bgneal@124 2 Smiley class and function.
bgneal@124 3 """
bgneal@124 4 import re
bgneal@124 5
bgneal@124 6 from django.utils.safestring import SafeData
bgneal@124 7 from django.utils.html import conditional_escape
bgneal@124 8
bgneal@124 9 from smiley.models import Smiley
bgneal@124 10
bgneal@124 11
bgneal@124 12 class Smilify(object):
bgneal@124 13 """
bgneal@124 14 A class to "smilify" text by replacing text with HTML img tags of smilies.
bgneal@124 15 """
bgneal@124 16 def __init__(self):
bgneal@124 17 self.map = Smiley.objects.get_smiley_map()
bgneal@124 18
bgneal@124 19 def convert(self, value, autoescape=False):
bgneal@124 20 if not autoescape or isinstance(value, SafeData):
bgneal@124 21 esc = lambda x: x
bgneal@124 22 else:
bgneal@124 23 esc = conditional_escape
bgneal@124 24
bgneal@124 25 words = value.split()
bgneal@124 26 for i, word in enumerate(words):
bgneal@124 27 if word in self.map:
bgneal@124 28 words[i] = self.map[word]
bgneal@124 29 else:
bgneal@124 30 words[i] = esc(words[i])
bgneal@124 31 return u' '.join(words)
bgneal@124 32
bgneal@124 33
bgneal@124 34 def smilify(value, autoescape=False):
bgneal@124 35 """
bgneal@124 36 A convenience function to "smilify" text by replacing text with HTML
bgneal@124 37 img tags of smilies.
bgneal@124 38 """
bgneal@124 39 s = Smilify()
bgneal@124 40 return s.convert(value, autoescape)
bgneal@124 41