bgneal@124: """ bgneal@211: Smiley classes and functions. bgneal@613: bgneal@124: """ bgneal@124: from django.utils.safestring import SafeData bgneal@124: from django.utils.html import conditional_escape bgneal@124: bgneal@124: from smiley.models import Smiley bgneal@124: bgneal@124: bgneal@211: class SmilifyHtml(object): bgneal@124: """ bgneal@211: A class to "smilify" text by replacing text with HTML img tags for smiley bgneal@211: images. bgneal@124: """ bgneal@124: def __init__(self): bgneal@124: self.map = Smiley.objects.get_smiley_map() bgneal@124: bgneal@211: def convert(self, value, autoescape=False): bgneal@128: """ bgneal@211: Converts and returns the supplied text with the HTML version of the bgneal@211: smileys. bgneal@128: """ bgneal@286: if not value: bgneal@286: return u'' bgneal@286: bgneal@124: if not autoescape or isinstance(value, SafeData): bgneal@124: esc = lambda x: x bgneal@124: else: bgneal@124: esc = conditional_escape bgneal@124: bgneal@124: words = value.split() bgneal@124: for i, word in enumerate(words): bgneal@124: if word in self.map: bgneal@211: words[i] = self.map[word] bgneal@124: else: bgneal@124: words[i] = esc(words[i]) bgneal@124: return u' '.join(words) bgneal@128: bgneal@211: bgneal@211: class SmilifyMarkdown(object): bgneal@211: """ bgneal@211: A class to "smilify" text by replacing text with Markdown image syntax for bgneal@211: smiley images. bgneal@211: """ bgneal@211: def __init__(self): bgneal@211: self.regexes = Smiley.objects.get_smiley_regexes() bgneal@211: bgneal@211: def convert(self, s): bgneal@128: """ bgneal@211: Returns a string copy of the input s that has the smiley codes replaced bgneal@211: with Markdown for smiley images. bgneal@128: """ bgneal@286: if not s: bgneal@286: return u'' bgneal@286: bgneal@211: for regex, repl in self.regexes: bgneal@211: s = regex.sub(repl, s) bgneal@211: return s bgneal@128: bgneal@124: bgneal@128: def smilify_html(value, autoescape=False): bgneal@124: """ bgneal@124: A convenience function to "smilify" text by replacing text with HTML bgneal@124: img tags of smilies. bgneal@124: """ bgneal@211: s = SmilifyHtml() bgneal@211: return s.convert(value, autoescape=autoescape) bgneal@124: