Package tdi :: Package markup :: Package text :: Module encoder
[frames] | no frames]

Source Code for Module tdi.markup.text.encoder

 1  # -*- coding: ascii -*- 
 2  u""" 
 3  :Copyright: 
 4   
 5   Copyright 2006 - 2013 
 6   Andr\xe9 Malo or his licensors, as applicable 
 7   
 8  :License: 
 9   
10   Licensed under the Apache License, Version 2.0 (the "License"); 
11   you may not use this file except in compliance with the License. 
12   You may obtain a copy of the License at 
13   
14       http://www.apache.org/licenses/LICENSE-2.0 
15   
16   Unless required by applicable law or agreed to in writing, software 
17   distributed under the License is distributed on an "AS IS" BASIS, 
18   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
19   See the License for the specific language governing permissions and 
20   limitations under the License. 
21   
22  ======================== 
23   Output Encoder Classes 
24  ======================== 
25   
26  This module provides output encoding logic. 
27  """ 
28  __author__ = u"Andr\xe9 Malo" 
29  __docformat__ = "restructuredtext en" 
30   
31  from tdi import interfaces as _interfaces 
32   
33   
34 -class TextEncoder(object):
35 """ Encoder for text output """ 36 __implements__ = [_interfaces.EncoderInterface] 37
38 - def __init__(self, encoding):
39 """ 40 Initialization 41 42 :Parameters: 43 `encoding` : ``str`` 44 The target encoding 45 """ 46 self.encoding = encoding
47
48 - def starttag(self, name, attr, closed):
49 """ :See: `EncoderInterface` """ 50 return (closed and "[[%s]]" or "[%s]") % (' '.join([name] + [ 51 value is not None and "%s=%s" % (key, value) or key 52 for key, value in attr 53 ]))
54
55 - def endtag(self, name):
56 """ :See: `EncoderInterface` """ 57 return "[/%s]" % name
58
59 - def name(self, name):
60 """ :See: `EncoderInterface` """ 61 if isinstance(name, unicode): 62 return name.encode(self.encoding, 'strict') 63 return name
64
65 - def attribute(self, value):
66 """ :See: `EncoderInterface` """ 67 if isinstance(value, unicode): 68 value = (value 69 .replace(u'"', u'\\"') 70 .encode(self.encoding, 'strict') 71 ) 72 else: 73 value = value.replace('"', '\\"') 74 return '"%s"' % value
75
76 - def content(self, value):
77 """ :See: `EncoderInterface` """ 78 if isinstance(value, unicode): 79 return (value 80 .encode(self.encoding, 'strict') 81 ) 82 return value
83
84 - def encode(self, value):
85 """ :See: `EncoderInterface` """ 86 return value.encode(self.encoding, 'strict')
87
88 - def escape(self, value):
89 """ :See: `EncoderInterface` """ 90 return value.replace('[', '[]')
91 92 93 from tdi import c 94 c = c.load('impl') 95 if c is not None: 96 TextEncoder = c.TextEncoder 97 del c 98