comparison gpp/smiley/__init__.py @ 128:48621ba5c385

Fixing #36, Smilify doesn't work when a smiley appears first before other text. Refactored the smiley system to produce markdown as well as HTML.
author Brian Neal <bgneal@gmail.com>
date Fri, 20 Nov 2009 01:43:32 +0000
parents 9c18250972d5
children 3a626c48e9ae
comparison
equal deleted inserted replaced
127:2d299909e074 128:48621ba5c385
9 from smiley.models import Smiley 9 from smiley.models import Smiley
10 10
11 11
12 class Smilify(object): 12 class Smilify(object):
13 """ 13 """
14 A class to "smilify" text by replacing text with HTML img tags of smilies. 14 A class to "smilify" text by replacing text with either HTML img tags
15 or markdown syntax for smiley images.
15 """ 16 """
17 HTML = 0
18 MARKDOWN = 1
19
16 def __init__(self): 20 def __init__(self):
17 self.map = Smiley.objects.get_smiley_map() 21 self.map = Smiley.objects.get_smiley_map()
18 22
19 def convert(self, value, autoescape=False): 23 def _convert(self, value, rep_index, autoescape=False):
24 """
25 Converts and returns the supplied text with either the
26 HTML or markdown version of the smileys according to the
27 output parameter.
28 """
20 if not autoescape or isinstance(value, SafeData): 29 if not autoescape or isinstance(value, SafeData):
21 esc = lambda x: x 30 esc = lambda x: x
22 else: 31 else:
23 esc = conditional_escape 32 esc = conditional_escape
24 33
25 words = value.split() 34 words = value.split()
26 for i, word in enumerate(words): 35 for i, word in enumerate(words):
27 if word in self.map: 36 if word in self.map:
28 words[i] = self.map[word] 37 words[i] = self.map[word][rep_index]
29 else: 38 else:
30 words[i] = esc(words[i]) 39 words[i] = esc(words[i])
31 return u' '.join(words) 40 return u' '.join(words)
41
42 def html(self, value, autoescape=False):
43 """
44 Converts the supplied text by replacing the smiley codes with
45 HTML img tags.
46 """
47 return self._convert(value, self.HTML, autoescape=autoescape)
48
49 def markdown(self, value, autoescape=False):
50 """
51 Converts the supplied text by replacing the smiley codes with
52 markdown image syntax.
53 """
54 return self._convert(value, self.MARKDOWN, autoescape=autoescape)
32 55
33 56
34 def smilify(value, autoescape=False): 57 def smilify_html(value, autoescape=False):
35 """ 58 """
36 A convenience function to "smilify" text by replacing text with HTML 59 A convenience function to "smilify" text by replacing text with HTML
37 img tags of smilies. 60 img tags of smilies.
38 """ 61 """
39 s = Smilify() 62 s = Smilify()
40 return s.convert(value, autoescape) 63 return s.html(value, autoescape=autoescape)
41 64
65
66 def smilify_markdown(value, autoescape=False):
67 """
68 A convenience function to "smilify" text by replacing text with
69 markdown syntax for the images of smilies.
70 """
71 s = Smilify()
72 return s.markdown(value, autoescape=autoescape)