annotate gpp/smiley/__init__.py @ 282:39664e661c69

Bug fix on r299 (#129).
author Brian Neal <bgneal@gmail.com>
date Mon, 04 Oct 2010 00:56:54 +0000
parents 3a626c48e9ae
children 72fd300685d5
rev   line source
bgneal@124 1 """
bgneal@211 2 Smiley classes and functions.
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@211 12 class SmilifyHtml(object):
bgneal@124 13 """
bgneal@211 14 A class to "smilify" text by replacing text with HTML img tags for smiley
bgneal@211 15 images.
bgneal@124 16 """
bgneal@124 17 def __init__(self):
bgneal@124 18 self.map = Smiley.objects.get_smiley_map()
bgneal@124 19
bgneal@211 20 def convert(self, value, autoescape=False):
bgneal@128 21 """
bgneal@211 22 Converts and returns the supplied text with the HTML version of the
bgneal@211 23 smileys.
bgneal@128 24 """
bgneal@124 25 if not autoescape or isinstance(value, SafeData):
bgneal@124 26 esc = lambda x: x
bgneal@124 27 else:
bgneal@124 28 esc = conditional_escape
bgneal@124 29
bgneal@124 30 words = value.split()
bgneal@124 31 for i, word in enumerate(words):
bgneal@124 32 if word in self.map:
bgneal@211 33 words[i] = self.map[word]
bgneal@124 34 else:
bgneal@124 35 words[i] = esc(words[i])
bgneal@124 36 return u' '.join(words)
bgneal@128 37
bgneal@211 38
bgneal@211 39 class SmilifyMarkdown(object):
bgneal@211 40 """
bgneal@211 41 A class to "smilify" text by replacing text with Markdown image syntax for
bgneal@211 42 smiley images.
bgneal@211 43 """
bgneal@211 44 def __init__(self):
bgneal@211 45 self.regexes = Smiley.objects.get_smiley_regexes()
bgneal@211 46
bgneal@211 47 def convert(self, s):
bgneal@128 48 """
bgneal@211 49 Returns a string copy of the input s that has the smiley codes replaced
bgneal@211 50 with Markdown for smiley images.
bgneal@128 51 """
bgneal@211 52 for regex, repl in self.regexes:
bgneal@211 53 s = regex.sub(repl, s)
bgneal@211 54 return s
bgneal@128 55
bgneal@124 56
bgneal@128 57 def smilify_html(value, autoescape=False):
bgneal@124 58 """
bgneal@124 59 A convenience function to "smilify" text by replacing text with HTML
bgneal@124 60 img tags of smilies.
bgneal@124 61 """
bgneal@211 62 s = SmilifyHtml()
bgneal@211 63 return s.convert(value, autoescape=autoescape)
bgneal@124 64