bgneal@124
|
1 """
|
bgneal@211
|
2 Smiley classes and functions.
|
bgneal@613
|
3
|
bgneal@124
|
4 """
|
bgneal@124
|
5 from django.utils.safestring import SafeData
|
bgneal@124
|
6 from django.utils.html import conditional_escape
|
bgneal@124
|
7
|
bgneal@124
|
8 from smiley.models import Smiley
|
bgneal@124
|
9
|
bgneal@124
|
10
|
bgneal@211
|
11 class SmilifyHtml(object):
|
bgneal@124
|
12 """
|
bgneal@211
|
13 A class to "smilify" text by replacing text with HTML img tags for smiley
|
bgneal@211
|
14 images.
|
bgneal@124
|
15 """
|
bgneal@124
|
16 def __init__(self):
|
bgneal@124
|
17 self.map = Smiley.objects.get_smiley_map()
|
bgneal@124
|
18
|
bgneal@211
|
19 def convert(self, value, autoescape=False):
|
bgneal@128
|
20 """
|
bgneal@211
|
21 Converts and returns the supplied text with the HTML version of the
|
bgneal@211
|
22 smileys.
|
bgneal@128
|
23 """
|
bgneal@286
|
24 if not value:
|
bgneal@286
|
25 return u''
|
bgneal@286
|
26
|
bgneal@124
|
27 if not autoescape or isinstance(value, SafeData):
|
bgneal@124
|
28 esc = lambda x: x
|
bgneal@124
|
29 else:
|
bgneal@124
|
30 esc = conditional_escape
|
bgneal@124
|
31
|
bgneal@124
|
32 words = value.split()
|
bgneal@124
|
33 for i, word in enumerate(words):
|
bgneal@124
|
34 if word in self.map:
|
bgneal@211
|
35 words[i] = self.map[word]
|
bgneal@124
|
36 else:
|
bgneal@124
|
37 words[i] = esc(words[i])
|
bgneal@124
|
38 return u' '.join(words)
|
bgneal@128
|
39
|
bgneal@211
|
40
|
bgneal@211
|
41 class SmilifyMarkdown(object):
|
bgneal@211
|
42 """
|
bgneal@211
|
43 A class to "smilify" text by replacing text with Markdown image syntax for
|
bgneal@211
|
44 smiley images.
|
bgneal@211
|
45 """
|
bgneal@211
|
46 def __init__(self):
|
bgneal@211
|
47 self.regexes = Smiley.objects.get_smiley_regexes()
|
bgneal@211
|
48
|
bgneal@211
|
49 def convert(self, s):
|
bgneal@128
|
50 """
|
bgneal@211
|
51 Returns a string copy of the input s that has the smiley codes replaced
|
bgneal@211
|
52 with Markdown for smiley images.
|
bgneal@128
|
53 """
|
bgneal@286
|
54 if not s:
|
bgneal@286
|
55 return u''
|
bgneal@286
|
56
|
bgneal@211
|
57 for regex, repl in self.regexes:
|
bgneal@211
|
58 s = regex.sub(repl, s)
|
bgneal@211
|
59 return s
|
bgneal@128
|
60
|
bgneal@124
|
61
|
bgneal@128
|
62 def smilify_html(value, autoescape=False):
|
bgneal@124
|
63 """
|
bgneal@124
|
64 A convenience function to "smilify" text by replacing text with HTML
|
bgneal@124
|
65 img tags of smilies.
|
bgneal@124
|
66 """
|
bgneal@211
|
67 s = SmilifyHtml()
|
bgneal@211
|
68 return s.convert(value, autoescape=autoescape)
|
bgneal@124
|
69
|