bgneal@124: """ bgneal@124: Smiley class and function. bgneal@124: """ bgneal@124: import re 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@124: class Smilify(object): bgneal@124: """ bgneal@128: A class to "smilify" text by replacing text with either HTML img tags bgneal@128: or markdown syntax for smiley images. bgneal@124: """ bgneal@128: HTML = 0 bgneal@128: MARKDOWN = 1 bgneal@128: bgneal@124: def __init__(self): bgneal@124: self.map = Smiley.objects.get_smiley_map() bgneal@124: bgneal@128: def _convert(self, value, rep_index, autoescape=False): bgneal@128: """ bgneal@128: Converts and returns the supplied text with either the bgneal@128: HTML or markdown version of the smileys according to the bgneal@128: output parameter. bgneal@128: """ 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@128: words[i] = self.map[word][rep_index] bgneal@124: else: bgneal@124: words[i] = esc(words[i]) bgneal@124: return u' '.join(words) bgneal@128: bgneal@128: def html(self, value, autoescape=False): bgneal@128: """ bgneal@128: Converts the supplied text by replacing the smiley codes with bgneal@128: HTML img tags. bgneal@128: """ bgneal@128: return self._convert(value, self.HTML, autoescape=autoescape) bgneal@128: bgneal@128: def markdown(self, value, autoescape=False): bgneal@128: """ bgneal@128: Converts the supplied text by replacing the smiley codes with bgneal@128: markdown image syntax. bgneal@128: """ bgneal@128: return self._convert(value, self.MARKDOWN, autoescape=autoescape) bgneal@124: 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@124: s = Smilify() bgneal@128: return s.html(value, autoescape=autoescape) bgneal@124: bgneal@128: bgneal@128: def smilify_markdown(value, autoescape=False): bgneal@128: """ bgneal@128: A convenience function to "smilify" text by replacing text with bgneal@128: markdown syntax for the images of smilies. bgneal@128: """ bgneal@128: s = Smilify() bgneal@128: return s.markdown(value, autoescape=autoescape)