Mercurial > public > sg101
comparison smiley/__init__.py @ 581:ee87ea74d46b
For Django 1.4, rearranged project structure for new manage.py.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Sat, 05 May 2012 17:10:48 -0500 |
parents | gpp/smiley/__init__.py@72fd300685d5 |
children | 0729c73d5761 |
comparison
equal
deleted
inserted
replaced
580:c525f3e0b5d0 | 581:ee87ea74d46b |
---|---|
1 """ | |
2 Smiley classes and functions. | |
3 """ | |
4 import re | |
5 | |
6 from django.utils.safestring import SafeData | |
7 from django.utils.html import conditional_escape | |
8 | |
9 from smiley.models import Smiley | |
10 | |
11 | |
12 class SmilifyHtml(object): | |
13 """ | |
14 A class to "smilify" text by replacing text with HTML img tags for smiley | |
15 images. | |
16 """ | |
17 def __init__(self): | |
18 self.map = Smiley.objects.get_smiley_map() | |
19 | |
20 def convert(self, value, autoescape=False): | |
21 """ | |
22 Converts and returns the supplied text with the HTML version of the | |
23 smileys. | |
24 """ | |
25 if not value: | |
26 return u'' | |
27 | |
28 if not autoescape or isinstance(value, SafeData): | |
29 esc = lambda x: x | |
30 else: | |
31 esc = conditional_escape | |
32 | |
33 words = value.split() | |
34 for i, word in enumerate(words): | |
35 if word in self.map: | |
36 words[i] = self.map[word] | |
37 else: | |
38 words[i] = esc(words[i]) | |
39 return u' '.join(words) | |
40 | |
41 | |
42 class SmilifyMarkdown(object): | |
43 """ | |
44 A class to "smilify" text by replacing text with Markdown image syntax for | |
45 smiley images. | |
46 """ | |
47 def __init__(self): | |
48 self.regexes = Smiley.objects.get_smiley_regexes() | |
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) | |
70 |