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

Source Code for Module tdi.markup.text.encoder

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