3 # COPYRIGHT (C) 1996-9 ROBIN FRIEDRICH email:Robin.Friedrich@pdq.net
4 # Permission to use, copy, modify, and distribute this software and
5 # its documentation for any purpose and without fee is hereby granted,
6 # provided that the above copyright notice appear in all copies and
7 # that both that copyright notice and this permission notice appear in
8 # supporting documentation.
9 # THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
10 # SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
11 # FITNESS, IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
12 # SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
13 # RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
14 # CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
15 # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 # Stripped down by Michael Hope <michaelh@juju.net.nz> to just support
20 """A class library for the generation of HTML documents.
22 Each HTML tag type has a supporting class which is responsible for
23 emitting itself as valid HTML formatted text. An attempt is made to
24 provide classes for newer HTML 3.2 and proposed tag elements. The
25 definitive reference for HTML tag elements can be found at
26 [W3C]. Also, I used the HTML book by Musciano and
27 Kennedy from [O Reilly] (2nd. Ed.) as the guiding reference.
29 The Document classes are container objects which act as a focal point
30 to populate all the contents of a particular web page. It also can
31 enforce consistent document formating according to the guidelines from
32 the [Yale Web Style Manual].
34 Features include customization of document template graphics / colors
35 through use of resource files, minimizing the need for modifying or
36 subclassing from the module source code. Support for tables, frames,
37 forms (persistent and otherwise) and client-side imagemaps are included.
39 A newer implementation for the Table support is now included,
40 TableLite(). In support of this there are new tag classes TD, TH, TR
41 and Caption. These class instances can be assembled in any way to
42 populate the TableLite container object.
44 .. [W3C] http://www.W3.org/TR/REC-html32.html
45 .. [O Reilly] http://www.oreilly.com/catalog/html3/index.html
46 .. [Yale Web Style Manual] http://info.med.yale.edu/caim/manual/contents.html
49 import string, re, time, os
51 __author__ = 'Robin Friedrich friedrich@pythonpros.com'
59 """Generate documents based on a template and a substitution mapping.
61 Must use Python 1.5 or newer. Uses re and the get method on dictionaries.
64 T = TemplateDocument('Xfile')
65 T.substitutions = {'month': ObjectY, 'town': 'Scarborough'}
68 A dictionary, or object that behaves like a dictionary, is assigned to the
69 *substitutions* attribute which has symbols as keys to objects. Upon every
70 occurance of these symbols surrounded by braces {} in the source template,
71 the corresponding value is converted to a string and substituted in the output.
73 For example, source text which looks like:
74 I lost my heart at {town} Fair.
76 I lost my heart at Scarborough Fair.
78 Symbols in braces which do not correspond to a key in the dictionary remain
81 An optional third argument to the class is a list or two strings to be
82 used as the delimiters instead of { } braces. They must be of the same
83 length; for example ['##+', '##'] is invalid.
85 def __init__(self, template, substitutions=None, **kw):
86 self.delimiters = ['{', '}']
87 self.__dict__.update(kw)
88 if len(self.delimiters) != 2:
89 raise ValueError("delimiter argument must be a pair of strings")
90 self.delimiter_width = len(self.delimiters[0])
91 delimiters = map(re.escape, self.delimiters)
92 self.subpatstr = delimiters[0] + "[\w_]+" + delimiters[1]
93 self.subpat = re.compile(self.subpatstr)
94 self.substitutions = substitutions or {}
95 self.set_template(template)
97 def set_template(self, template):
98 self.source = template
101 return self.substitutions.keys()
103 def __setitem__(self, name, value):
104 self.substitutions[name] = value
106 def __getitem__(self, name):
107 return self.substitutions[name]
110 return self._sub(self.source)
112 def _sub(self, source, subs=None):
113 """Perform source text substitutions.
115 *source* string containing template source text
116 *subs* mapping of symbols to replacement values
118 substitutions = subs or self.substitutions
119 dw = self.delimiter_width
122 matched = self.subpat.search(source[i:])
124 a, b = matched.span()
125 output.append(source[i:i+a])
126 # using the new get method for dicts in 1.5
127 output.append(str(substitutions.get(
128 source[i+a+dw:i+b-dw], source[i+a:i+b])))
130 matched = self.subpat.search(source[i:])
132 output.append(source[i:])
133 return string.join(output, '')
135 def write(self, filename = None):
136 """Emit the Document HTML to a file or standard output.
138 Will not overwrite file is it exists and is textually the same.
139 In Unix you can use environment variables in filenames.
140 Will print to stdout if no argument given.
143 if os.path.exists(filename):
145 if compare_s2f(s, filename):
146 f = open(filename, 'w')
150 f = open(filename, 'w')
155 sys.stdout.write(str(self))
157 class TemplateDocument(StringTemplate):
158 """Generate documents based on a template and a substitution mapping.
160 Must use Python 1.5 or newer. Uses re and the get method on dictionaries.
163 T = TemplateDocument('Xfile')
164 T.substitutions = {'month': ObjectY, 'town': 'Scarborough'}
165 T.write('Maine.html')
167 A dictionary, or object that behaves like a dictionary, is assigned to the
168 *substitutions* attribute which has symbols as keys to objects. Upon every
169 occurance of these symbols surrounded by braces {} in the source template,
170 the corresponding value is converted to a string and substituted in the output.
172 For example, source text which looks like:
173 I lost my heart at {town} Fair.
175 I lost my heart at Scarborough Fair.
177 Symbols in braces which do not correspond to a key in the dictionary remain
180 An optional third argument to the class is a list or two strings to be
181 used as the delimiters instead of { } braces. They must be of the same
182 length; for example ['##+', '##'] is invalid.
184 def set_template(self, template):
186 self.source = f.read()
189 def compare_s2f(s, f2):
190 """Helper to compare a string to a file, return 0 if they are equal."""
198 b1 = s[i: i + BUFSIZE]
202 b2 = fp2.read(BUFSIZE)
203 if not b1 and not b2: return 0