comparison smiley/utils.py @ 925:98d2388b6bb2

Smiley app refactor for Django 1.7.7 upgrade.
author Brian Neal <bgneal@gmail.com>
date Sun, 12 Apr 2015 21:08:56 -0500
parents smiley/__init__.py@7429c98c8ece
children
comparison
equal deleted inserted replaced
924:78b459d4ab17 925:98d2388b6bb2
1 """
2 Smiley classes and functions.
3
4 """
5 from django.utils.safestring import SafeData
6 from django.utils.html import conditional_escape
7
8 from models import Smiley
9
10
11 class SmilifyHtml(object):
12 """
13 A class to "smilify" text by replacing text with HTML img tags for smiley
14 images.
15 """
16 def __init__(self):
17 self.map = Smiley.objects.get_smiley_map()
18
19 def convert(self, value, autoescape=False):
20 """
21 Converts and returns the supplied text with the HTML version of the
22 smileys.
23 """
24 if not value:
25 return u''
26
27 if not autoescape or isinstance(value, SafeData):
28 esc = lambda x: x
29 else:
30 esc = conditional_escape
31
32 words = value.split()
33 for i, word in enumerate(words):
34 if word in self.map:
35 words[i] = self.map[word]
36 else:
37 words[i] = esc(words[i])
38 return u' '.join(words)
39
40
41 class SmilifyMarkdown(object):
42 """
43 A class to "smilify" text by replacing text with Markdown image syntax for
44 smiley images.
45 """
46 def __init__(self, relative_urls=True):
47 self.regexes = Smiley.objects.get_smiley_regexes(
48 relative_urls=relative_urls)
49
50 def convert(self, s):
51 """
52 Returns a string copy of the input s that has the smiley codes replaced
53 with Markdown for smiley images.
54 """
55 if not s:
56 return u''
57
58 for regex, repl in self.regexes:
59 s = regex.sub(repl, s)
60 return s
61
62
63 def smilify_html(value, autoescape=False):
64 """
65 A convenience function to "smilify" text by replacing text with HTML
66 img tags of smilies.
67 """
68 s = SmilifyHtml()
69 return s.convert(value, autoescape=autoescape)