2 # $Id: Filters.py,v 1.32 2007/03/29 19:31:15 tavis_rudd Exp $
3 """Filters for the #filter directive; output filters Cheetah's $placeholders .
6 ================================================================================
7 Author: Tavis Rudd <tavis@damnsimple.com>
8 Version: $Revision: 1.32 $
10 Last Revision Date: $Date: 2007/03/29 19:31:15 $
12 __author__
= "Tavis Rudd <tavis@damnsimple.com>"
13 __revision__
= "$Revision: 1.32 $"[11:-2]
15 # Additional entities WebSafe knows how to transform. No need to include
16 # '<', '>' or '&' since those will have been done already.
17 webSafeEntities
= {' ': ' ', '"': '"'}
19 class Error(Exception):
22 ##################################################
26 """A baseclass for the Cheetah Filters."""
28 def __init__(self
, template
=None):
29 """Setup a reference to the template that is using the filter instance.
30 This reference isn't used by any of the standard filters, but is
31 available to Filter subclasses, should they need it.
33 Subclasses should call this method.
35 self
.template
= template
42 """Pass Unicode strings through unmolested, unless an encoding is specified.
44 if isinstance(val
, unicode):
46 filtered
= val
.encode(encoding
)
55 RawOrEncodedUnicode
= Filter
57 ##################################################
60 class EncodeUnicode(Filter
):
65 """Encode Unicode strings, by default in UTF-8.
67 >>> import Cheetah.Template
68 >>> t = Cheetah.Template.Template('''
70 ... ${myvar, encoding='utf16'}
71 ... ''', searchList=[{'myvar': u'Asni\xe8res'}],
72 ... filter='EncodeUnicode')
75 if isinstance(val
, unicode):
76 filtered
= val
.encode(encoding
)
84 def filter(self
, val
, **kw
):
85 """Replace None with '' and cut off at maxlen."""
87 output
= super(MaxLen
, self
).filter(val
, **kw
)
88 if kw
.has_key('maxlen') and len(output
) > kw
['maxlen']:
89 return output
[:kw
['maxlen']]
92 class WebSafe(Filter
):
93 """Escape HTML entities in $placeholders.
95 def filter(self
, val
, **kw
):
96 s
= super(WebSafe
, self
).filter(val
, **kw
)
97 # These substitutions are copied from cgi.escape().
98 s
= s
.replace("&", "&") # Must be done first!
99 s
= s
.replace("<", "<")
100 s
= s
.replace(">", ">")
101 # Process the additional transformations if any.
102 if kw
.has_key('also'):
104 entities
= webSafeEntities
# Global variable.
106 if entities
.has_key(k
):
116 """Strip leading/trailing whitespace but preserve newlines.
118 This filter goes through the value line by line, removing leading and
119 trailing whitespace on each line. It does not strip newlines, so every
120 input line corresponds to one output line, with its trailing newline intact.
122 We do not use val.split('\n') because that would squeeze out consecutive
123 blank lines. Instead, we search for each newline individually. This
124 makes us unable to use the fast C .split method, but it makes the filter
125 much more widely useful.
127 This filter is intended to be usable both with the #filter directive and
128 with the proposed #sed directive (which has not been ratified yet.)
130 def filter(self
, val
, **kw
):
131 s
= super(Strip
, self
).filter(val
, **kw
)
133 start
= 0 # The current line will be s[start:end].
134 while 1: # Loop through each line.
135 end
= s
.find('\n', start
) # Find next newline.
136 if end
== -1: # If no more newlines.
138 chunk
= s
[start
:end
].strip()
142 # Write the unfinished portion after the last newline, if any.
143 chunk
= s
[start
:].strip()
145 return "".join(result
)
147 class StripSqueeze(Filter
):
148 """Canonicalizes every chunk of whitespace to a single space.
150 Strips leading/trailing whitespace. Removes all newlines, so multi-line
151 input is joined into one ling line with NO trailing newline.
153 def filter(self
, val
, **kw
):
154 s
= super(StripSqueeze
, self
).filter(val
, **kw
)
158 ##################################################
159 ## MAIN ROUTINE -- testing
163 s2
= " asdf \n\t 1 2 3\n"
164 print "WebSafe INPUT:", `s1`
165 print " WebSafe:", `
WebSafe().filter(s1
)`
168 print " Strip INPUT:", `s2`
169 print " Strip:", `
Strip().filter(s2
)`
170 print "StripSqueeze:", `
StripSqueeze().filter(s2
)`
172 print "Unicode:", `
EncodeUnicode().filter(u
'aoeu12345\u1234')`
174 if __name__
== "__main__": test()
176 # vim: shiftwidth=4 tabstop=4 expandtab