annotate markup/template.py @ 6:5da45906dda7

Simplified implementation of `py:content` directive.
author cmlenz
date Sun, 04 Jun 2006 10:46:14 +0000
parents 1add946decb8
children c5890ef863ba
rev   line source
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
1 # -*- coding: utf-8 -*-
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
2 #
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
3 # Copyright (C) 2006 Christopher Lenz
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
4 # All rights reserved.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
5 #
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
6 # This software is licensed as described in the file COPYING, which
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
7 # you should have received as part of this distribution. The terms
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
8 # are also available at http://trac.edgewall.com/license.html.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
9 #
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
10 # This software consists of voluntary contributions made by many
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
11 # individuals. For the exact contribution history, see the revision
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
12 # history and logs, available at http://projects.edgewall.com/trac/.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
13
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
14 """Template engine that is compatible with Kid (http://kid.lesscode.org) to a
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
15 certain extent.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
16
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
17 Differences include:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
18 * No generation of Python code for a template; the template is "interpreted"
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
19 * No support for <?python ?> processing instructions
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
20 * Expressions are evaluated in a more flexible manner, meaning you can use e.g.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
21 attribute access notation to access items in a dictionary, etc
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
22 * Use of XInclude and match templates instead of Kid's py:extends/py:layout
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
23 directives
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
24 * Real (thread-safe) search path support
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
25 * No dependency on ElementTree (due to the lack of pos info)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
26 * The original pos of parse events is kept throughout the processing
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
27 pipeline, so that errors can be tracked back to a specific line/column in
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
28 the template file
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
29 * py:match directives use (basic) XPath expressions to match against input
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
30 nodes, making match templates more powerful while keeping the syntax simple
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
31
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
32 Todo items:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
33 * Improved error reporting
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
34 * Support for using directives as elements and not just as attributes, reducing
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
35 the need for wrapper elements with py:strip=""
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
36 * Support for py:choose/py:when/py:otherwise (similar to XSLT)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
37 * Support for list comprehensions and generator expressions in expressions
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
38
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
39 Random thoughts:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
40 * Is there any need to support py:extends and/or py:layout?
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
41 * Could we generate byte code from expressions?
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
42 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
43
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
44 import compiler
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
45 from itertools import chain
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
46 import os
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
47 import re
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
48 from StringIO import StringIO
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
49
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
50 from markup.core import Attributes, Stream
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
51 from markup.eval import Expression
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
52 from markup.filters import EvalFilter, IncludeFilter, MatchFilter, \
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
53 WhitespaceFilter
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
54 from markup.input import HTML, XMLParser, XML
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
55
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
56 __all__ = ['Context', 'BadDirectiveError', 'TemplateError',
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
57 'TemplateSyntaxError', 'TemplateNotFound', 'Template',
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
58 'TemplateLoader']
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
59
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
60
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
61 class TemplateError(Exception):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
62 """Base exception class for errors related to template processing."""
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
63
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
64
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
65 class TemplateSyntaxError(TemplateError):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
66 """Exception raised when an expression in a template causes a Python syntax
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
67 error."""
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
68
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
69 def __init__(self, message, filename='<string>', lineno=-1, offset=-1):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
70 if isinstance(message, SyntaxError) and message.lineno is not None:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
71 message = str(message).replace(' (line %d)' % message.lineno, '')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
72 TemplateError.__init__(self, message)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
73 self.filename = filename
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
74 self.lineno = lineno
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
75 self.offset = offset
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
76
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
77
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
78 class BadDirectiveError(TemplateSyntaxError):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
79 """Exception raised when an unknown directive is encountered when parsing
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
80 a template.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
81
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
82 An unknown directive is any attribute using the namespace for directives,
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
83 with a local name that doesn't match any registered directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
84 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
85
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
86 def __init__(self, name, filename='<string>', lineno=-1):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
87 TemplateSyntaxError.__init__(self, 'Bad directive "%s"' % name.localname,
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
88 filename, lineno)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
89
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
90
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
91 class TemplateNotFound(TemplateError):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
92 """Exception raised when a specific template file could not be found."""
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
93
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
94 def __init__(self, name, search_path):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
95 TemplateError.__init__(self, 'Template "%s" not found' % name)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
96 self.search_path = search_path
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
97
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
98
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
99 class Context(object):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
100 """A container for template input data.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
101
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
102 A context provides a stack of scopes. Template directives such as loops can
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
103 push a new scope on the stack with data that should only be available
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
104 inside the loop. When the loop terminates, that scope can get popped off
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
105 the stack again.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
106
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
107 >>> ctxt = Context(one='foo', other=1)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
108 >>> ctxt.get('one')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
109 'foo'
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
110 >>> ctxt.get('other')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
111 1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
112 >>> ctxt.push(one='frost')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
113 >>> ctxt.get('one')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
114 'frost'
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
115 >>> ctxt.get('other')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
116 1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
117 >>> ctxt.pop()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
118 >>> ctxt.get('one')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
119 'foo'
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
120 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
121
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
122 def __init__(self, **data):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
123 self.stack = [data]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
124
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
125 def __getitem__(self, key):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
126 """Get a variable's value, starting at the current context and going
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
127 upward.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
128 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
129 return self.get(key)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
130
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
131 def __repr__(self):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
132 return repr(self.stack)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
133
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
134 def __setitem__(self, key, value):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
135 """Set a variable in the current context."""
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
136 self.stack[0][key] = value
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
137
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
138 def get(self, key):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
139 for frame in self.stack:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
140 if key in frame:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
141 return frame[key]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
142
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
143 def push(self, **data):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
144 self.stack.insert(0, data)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
145
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
146 def pop(self):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
147 assert self.stack, 'Pop from empty context stack'
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
148 self.stack.pop(0)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
149
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
150
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
151 class Directive(object):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
152 """Abstract base class for template directives.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
153
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
154 A directive is basically a callable that takes two parameters: `ctxt` is
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
155 the template data context, and `stream` is an iterable over the events that
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
156 the directive applies to.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
157
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
158 Directives can be "anonymous" or "registered". Registered directives can be
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
159 applied by the template author using an XML attribute with the
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
160 corresponding name in the template. Such directives should be subclasses of
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
161 this base class that can be instantiated with two parameters: `template`
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
162 is the `Template` instance, and `value` is the value of the directive
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
163 attribute.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
164
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
165 Anonymous directives are simply functions conforming to the protocol
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
166 described above, and can only be applied programmatically (for example by
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
167 template filters).
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
168 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
169 __slots__ = ['expr']
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
170
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
171 def __init__(self, template, value, pos):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
172 self.expr = value and Expression(value) or None
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
173
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
174 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
175 raise NotImplementedError
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
176
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
177 def __repr__(self):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
178 expr = ''
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
179 if self.expr is not None:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
180 expr = ' "%s"' % self.expr.source
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
181 return '<%s%s>' % (self.__class__.__name__, expr)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
182
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
183
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
184 class AttrsDirective(Directive):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
185 """Implementation of the `py:attrs` template directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
186
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
187 The value of the `py:attrs` attribute should be a dictionary. The keys and
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
188 values of that dictionary will be added as attributes to the element:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
189
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
190 >>> ctxt = Context(foo={'class': 'collapse'})
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
191 >>> tmpl = Template('''<ul xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
192 ... <li py:attrs="foo">Bar</li>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
193 ... </ul>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
194 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
195 <ul>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
196 <li class="collapse">Bar</li>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
197 </ul>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
198
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
199 If the value evaluates to `None` (or any other non-truth value), no
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
200 attributes are added:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
201
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
202 >>> ctxt = Context(foo=None)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
203 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
204 <ul>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
205 <li>Bar</li>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
206 </ul>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
207 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
208 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
209 kind, (tag, attrib), pos = stream.next()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
210 attrs = self.expr.evaluate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
211 if attrs:
5
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
212 attrib = Attributes(attrib[:])
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
213 if not isinstance(attrs, list): # assume it's a dict
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
214 attrs = attrs.items()
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
215 for name, value in attrs:
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
216 if value is None:
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
217 attrib.remove(name)
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
218 else:
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
219 attrib.set(name, unicode(value).strip())
1add946decb8 Improved `py:attrs` directive so that it removes existing attributes if they evaluate to `None` (AFAICT matching Kid behavior).
cmlenz
parents: 1
diff changeset
220 yield kind, (tag, attrib), pos
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
221 for event in stream:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
222 yield event
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
223
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
224
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
225 class ContentDirective(Directive):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
226 """Implementation of the `py:content` template directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
227
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
228 This directive replaces the content of the element with the result of
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
229 evaluating the value of the `py:content` attribute:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
230
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
231 >>> ctxt = Context(bar='Bye')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
232 >>> tmpl = Template('''<ul xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
233 ... <li py:content="bar">Hello</li>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
234 ... </ul>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
235 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
236 <ul>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
237 <li>Bye</li>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
238 </ul>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
239 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
240 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
241 kind, data, pos = stream.next()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
242 if kind is Stream.START:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
243 yield kind, data, pos # emit start tag
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
244 yield Stream.EXPR, self.expr, pos
6
5da45906dda7 Simplified implementation of `py:content` directive.
cmlenz
parents: 5
diff changeset
245 previous = stream.next()
5da45906dda7 Simplified implementation of `py:content` directive.
cmlenz
parents: 5
diff changeset
246 for event in stream:
5da45906dda7 Simplified implementation of `py:content` directive.
cmlenz
parents: 5
diff changeset
247 previous = event
5da45906dda7 Simplified implementation of `py:content` directive.
cmlenz
parents: 5
diff changeset
248 else:
1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
249 if previous is not None:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
250 yield previous
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
251
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
252
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
253 class DefDirective(Directive):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
254 """Implementation of the `py:def` template directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
255
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
256 This directive can be used to create "Named Template Functions", which
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
257 are template snippets that are not actually output during normal
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
258 processing, but rather can be expanded from expressions in other places
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
259 in the template.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
260
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
261 A named template function can be used just like a normal Python function
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
262 from template expressions:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
263
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
264 >>> ctxt = Context(bar='Bye')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
265 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
266 ... <p py:def="echo(greeting, name='world')" class="message">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
267 ... ${greeting}, ${name}!
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
268 ... </p>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
269 ... ${echo('hi', name='you')}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
270 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
271 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
272 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
273 <p class="message">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
274 hi, you!
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
275 </p>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
276 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
277
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
278 >>> ctxt = Context(bar='Bye')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
279 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
280 ... <p py:def="echo(greeting, name='world')" class="message">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
281 ... ${greeting}, ${name}!
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
282 ... </p>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
283 ... <div py:replace="echo('hello')"></div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
284 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
285 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
286 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
287 <p class="message">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
288 hello, world!
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
289 </p>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
290 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
291 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
292 __slots__ = ['name', 'args', 'defaults', 'stream']
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
293
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
294 def __init__(self, template, args, pos):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
295 Directive.__init__(self, template, None, pos)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
296 ast = compiler.parse(args, 'eval').node
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
297 self.args = []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
298 self.defaults = {}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
299 if isinstance(ast, compiler.ast.CallFunc):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
300 self.name = ast.node.name
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
301 for arg in ast.args:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
302 if isinstance(arg, compiler.ast.Keyword):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
303 self.args.append(arg.name)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
304 self.defaults[arg.name] = arg.expr.value
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
305 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
306 self.args.append(arg.name)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
307 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
308 self.name = ast.name
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
309 self.stream = []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
310
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
311 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
312 self.stream = list(stream)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
313 ctxt[self.name] = lambda *args, **kwargs: self._exec(ctxt, *args,
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
314 **kwargs)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
315 return []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
316
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
317 def _exec(self, ctxt, *args, **kwargs):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
318 scope = {}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
319 args = list(args) # make mutable
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
320 for name in self.args:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
321 if args:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
322 scope[name] = args.pop(0)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
323 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
324 scope[name] = kwargs.pop(name, self.defaults.get(name))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
325 ctxt.push(**scope)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
326 for event in self.stream:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
327 yield event
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
328 ctxt.pop()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
329
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
330
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
331 class ForDirective(Directive):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
332 """Implementation of the `py:for` template directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
333
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
334 >>> ctxt = Context(items=[1, 2, 3])
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
335 >>> tmpl = Template('''<ul xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
336 ... <li py:for="item in items">${item}</li>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
337 ... </ul>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
338 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
339 <ul>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
340 <li>1</li><li>2</li><li>3</li>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
341 </ul>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
342 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
343 __slots__ = ['targets']
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
344
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
345 def __init__(self, template, value, pos):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
346 targets, expr_source = value.split(' in ', 1)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
347 self.targets = [str(name.strip()) for name in targets.split(',')]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
348 Directive.__init__(self, template, expr_source, pos)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
349
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
350 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
351 iterable = self.expr.evaluate(ctxt, [])
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
352 if iterable is not None:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
353 stream = list(stream)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
354 for item in iter(iterable):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
355 if len(self.targets) == 1:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
356 item = [item]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
357 scope = {}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
358 for idx, name in enumerate(self.targets):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
359 scope[name] = item[idx]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
360 ctxt.push(**scope)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
361 for event in stream:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
362 yield event
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
363 ctxt.pop()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
364
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
365 def __repr__(self):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
366 return '<%s "%s in %s">' % (self.__class__.__name__,
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
367 ', '.join(self.targets), self.expr.source)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
368
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
369
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
370 class IfDirective(Directive):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
371 """Implementation of the `py:if` template directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
372
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
373 >>> ctxt = Context(foo=True, bar='Hello')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
374 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
375 ... <b py:if="foo">${bar}</b>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
376 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
377 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
378 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
379 <b>Hello</b>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
380 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
381 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
382 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
383 if self.expr.evaluate(ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
384 return stream
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
385 return []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
386
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
387
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
388 class MatchDirective(Directive):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
389 """Implementation of the `py:match` template directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
390
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
391 >>> ctxt = Context()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
392 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
393 ... <span py:match="div/greeting">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
394 ... Hello ${select('@name')}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
395 ... </span>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
396 ... <greeting name="Dude" />
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
397 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
398 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
399 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
400 <span>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
401 Hello Dude
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
402 </span>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
403 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
404 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
405 __slots__ = ['path', 'stream']
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
406
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
407 def __init__(self, template, value, pos):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
408 Directive.__init__(self, template, None, pos)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
409 template.filters.append(MatchFilter(value, self._handle_match))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
410 self.path = value
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
411 self.stream = []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
412
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
413 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
414 self.stream = list(stream)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
415 return []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
416
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
417 def __repr__(self):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
418 return '<%s "%s">' % (self.__class__.__name__, self.path)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
419
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
420 def _handle_match(self, orig_stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
421 ctxt.push(select=lambda path: Stream(orig_stream).select(path))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
422 for event in self.stream:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
423 yield event
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
424 ctxt.pop()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
425
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
426
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
427 class ReplaceDirective(Directive):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
428 """Implementation of the `py:replace` template directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
429
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
430 >>> ctxt = Context(bar='Bye')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
431 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
432 ... <span py:replace="bar">Hello</span>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
433 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
434 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
435 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
436 Bye
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
437 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
438
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
439 This directive is equivalent to `py:content` combined with `py:strip`,
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
440 providing a less verbose way to achieve the same effect:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
441
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
442 >>> ctxt = Context(bar='Bye')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
443 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
444 ... <span py:content="bar" py:strip="">Hello</span>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
445 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
446 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
447 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
448 Bye
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
449 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
450 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
451 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
452 kind, data, pos = stream.next()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
453 yield Stream.EXPR, self.expr, pos
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
454
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
455
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
456 class StripDirective(Directive):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
457 """Implementation of the `py:strip` template directive.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
458
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
459 When the value of the `py:strip` attribute evaluates to `True`, the element
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
460 is stripped from the output
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
461
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
462 >>> ctxt = Context()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
463 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
464 ... <div py:strip="True"><b>foo</b></div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
465 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
466 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
467 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
468 <b>foo</b>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
469 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
470
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
471 On the other hand, when the attribute evaluates to `False`, the element is
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
472 not stripped:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
473
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
474 >>> ctxt = Context()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
475 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
476 ... <div py:strip="False"><b>foo</b></div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
477 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
478 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
479 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
480 <div><b>foo</b></div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
481 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
482
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
483 Leaving the attribute value empty is equivalent to a truth value:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
484
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
485 >>> ctxt = Context()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
486 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
487 ... <div py:strip=""><b>foo</b></div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
488 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
489 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
490 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
491 <b>foo</b>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
492 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
493
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
494 This directive is particulary interesting for named template functions or
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
495 match templates that do not generate a top-level element:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
496
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
497 >>> ctxt = Context()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
498 >>> tmpl = Template('''<div xmlns:py="http://purl.org/kid/ns#">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
499 ... <div py:def="echo(what)" py:strip="">
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
500 ... <b>${what}</b>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
501 ... </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
502 ... ${echo('foo')}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
503 ... </div>''')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
504 >>> print tmpl.generate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
505 <div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
506 <b>foo</b>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
507 </div>
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
508 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
509 def __call__(self, stream, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
510 if self.expr:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
511 strip = self.expr.evaluate(ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
512 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
513 strip = True
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
514 if strip:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
515 stream.next() # skip start tag
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
516 # can ignore StopIteration since it will just break from this
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
517 # generator
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
518 previous = stream.next()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
519 for event in stream:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
520 yield previous
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
521 previous = event
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
522 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
523 for event in stream:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
524 yield event
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
525
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
526
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
527 class Template(object):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
528 """Can parse a template and transform it into the corresponding output
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
529 based on context data.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
530 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
531 NAMESPACE = 'http://purl.org/kid/ns#'
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
532
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
533 directives = [('def', DefDirective),
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
534 ('match', MatchDirective),
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
535 ('for', ForDirective),
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
536 ('if', IfDirective),
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
537 ('replace', ReplaceDirective),
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
538 ('content', ContentDirective),
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
539 ('attrs', AttrsDirective),
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
540 ('strip', StripDirective)]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
541 _dir_by_name = dict(directives)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
542 _dir_order = [directive[1] for directive in directives]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
543
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
544 def __init__(self, source, filename=None):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
545 """Initialize a template from either a string or a file-like object."""
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
546 if isinstance(source, basestring):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
547 self.source = StringIO(source)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
548 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
549 self.source = source
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
550 self.filename = filename or '<string>'
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
551
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
552 self.pre_filters = [EvalFilter()]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
553 self.filters = []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
554 self.post_filters = [WhitespaceFilter()]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
555 self.parse()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
556
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
557 def __repr__(self):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
558 return '<%s "%s">' % (self.__class__.__name__,
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
559 os.path.basename(self.filename))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
560
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
561 def parse(self):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
562 """Parse the template.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
563
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
564 The parsing stage parses the XML template and constructs a list of
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
565 directives that will be executed in the render stage. The input is
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
566 split up into literal output (markup that does not depend on the
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
567 context data) and actual directives (commands or variable
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
568 substitution).
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
569 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
570 stream = [] # list of events of the "compiled" template
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
571 dirmap = {} # temporary mapping of directives to elements
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
572 ns_prefix = {}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
573 depth = 0
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
574
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
575 for kind, data, pos in XMLParser(self.source):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
576
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
577 if kind is Stream.START_NS:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
578 # Strip out the namespace declaration for template directives
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
579 prefix, uri = data
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
580 if uri == self.NAMESPACE:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
581 ns_prefix[prefix] = uri
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
582 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
583 stream.append((kind, data, pos))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
584
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
585 elif kind is Stream.END_NS:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
586 if data in ns_prefix:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
587 del ns_prefix[data]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
588 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
589 stream.append((kind, data, pos))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
590
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
591 elif kind is Stream.START:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
592 # Record any directive attributes in start tags
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
593 tag, attrib = data
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
594 directives = []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
595 new_attrib = []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
596 for name, value in attrib:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
597 if name.namespace == self.NAMESPACE:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
598 cls = self._dir_by_name.get(name.localname)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
599 if cls is None:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
600 raise BadDirectiveError(name, self.filename, pos[0])
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
601 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
602 directives.append(cls(self, value, pos))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
603 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
604 value = list(self._interpolate(value, *pos))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
605 new_attrib.append((name, value))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
606 if directives:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
607 directives.sort(lambda a, b: cmp(self._dir_order.index(a.__class__),
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
608 self._dir_order.index(b.__class__)))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
609 dirmap[(depth, tag)] = (directives, len(stream))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
610
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
611 stream.append((kind, (tag, Attributes(new_attrib)), pos))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
612 depth += 1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
613
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
614 elif kind is Stream.END:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
615 depth -= 1
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
616 stream.append((kind, data, pos))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
617
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
618 # If there have have directive attributes with the corresponding
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
619 # start tag, move the events inbetween into a "subprogram"
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
620 if (depth, data) in dirmap:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
621 directives, start_offset = dirmap.pop((depth, data))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
622 substream = stream[start_offset:]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
623 stream[start_offset:] = [(Stream.SUB,
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
624 (directives, substream), pos)]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
625
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
626 elif kind is Stream.TEXT:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
627 for kind, data, pos in self._interpolate(data, *pos):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
628 stream.append((kind, data, pos))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
629
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
630 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
631 stream.append((kind, data, pos))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
632
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
633 self.stream = stream
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
634
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
635 def generate(self, ctxt):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
636 """Transform the template based on the given context data."""
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
637
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
638 def _transform(stream):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
639 # Apply pre and runtime filters
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
640 for filter_ in chain(self.pre_filters, self.filters):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
641 stream = filter_(iter(stream), ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
642
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
643 try:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
644 for kind, data, pos in stream:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
645
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
646 if kind is Stream.SUB:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
647 # This event is a list of directives and a list of
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
648 # nested events to which those directives should be
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
649 # applied
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
650 directives, substream = data
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
651 directives.reverse()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
652 for directive in directives:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
653 substream = directive(iter(substream), ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
654 for event in _transform(iter(substream)):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
655 yield event
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
656
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
657 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
658 yield kind, data, pos
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
659 except SyntaxError, err:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
660 raise TemplateSyntaxError(err, self.filename, pos[0],
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
661 pos[1] + (err.offset or 0))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
662
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
663 stream = _transform(self.stream)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
664
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
665 # Apply post-filters
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
666 for filter_ in self.post_filters:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
667 stream = filter_(iter(stream), ctxt)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
668
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
669 return Stream(stream)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
670
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
671 _FULL_EXPR_RE = re.compile(r'(?<!\$)\$\{(.+?)\}')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
672 _SHORT_EXPR_RE = re.compile(r'(?<!\$)\$([a-zA-Z][a-zA-Z0-9_\.]*)')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
673
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
674 def _interpolate(cls, text, lineno=-1, offset=-1):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
675 """Parse the given string and extract expressions.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
676
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
677 This method returns a list containing both literal text and `Expression`
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
678 objects.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
679
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
680 @param text: the text to parse
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
681 @param lineno: the line number at which the text was found (optional)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
682 @param offset: the column number at which the text starts in the source
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
683 (optional)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
684 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
685 patterns = [cls._FULL_EXPR_RE, cls._SHORT_EXPR_RE]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
686 def _interpolate(text):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
687 for idx, group in enumerate(patterns.pop(0).split(text)):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
688 if idx % 2:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
689 yield Stream.EXPR, Expression(group), (lineno, offset)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
690 elif group:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
691 if patterns:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
692 for result in _interpolate(group):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
693 yield result
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
694 else:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
695 yield Stream.TEXT, group.replace('$$', '$'), \
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
696 (lineno, offset)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
697 return _interpolate(text)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
698 _interpolate = classmethod(_interpolate)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
699
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
700
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
701 class TemplateLoader(object):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
702 """Responsible for loading templates from files on the specified search
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
703 path.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
704
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
705 >>> import tempfile
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
706 >>> fd, path = tempfile.mkstemp(suffix='.html', prefix='template')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
707 >>> os.write(fd, '<p>$var</p>')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
708 11
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
709 >>> os.close(fd)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
710
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
711 The template loader accepts a list of directory paths that are then used
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
712 when searching for template files, in the given order:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
713
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
714 >>> loader = TemplateLoader([os.path.dirname(path)])
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
715
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
716 The `load()` method first checks the template cache whether the requested
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
717 template has already been loaded. If not, it attempts to locate the
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
718 template file, and returns the corresponding `Template` object:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
719
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
720 >>> template = loader.load(os.path.basename(path))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
721 >>> isinstance(template, Template)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
722 True
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
723
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
724 Template instances are cached: requesting a template with the same name
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
725 results in the same instance being returned:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
726
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
727 >>> loader.load(os.path.basename(path)) is template
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
728 True
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
729 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
730 def __init__(self, search_path=None, auto_reload=False):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
731 """Create the template laoder.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
732
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
733 @param search_path: a list of absolute path names that should be
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
734 searched for template files
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
735 @param auto_reload: whether to check the last modification time of
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
736 template files, and reload them if they have changed
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
737 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
738 self.search_path = search_path
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
739 if self.search_path is None:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
740 self.search_path = []
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
741 self.auto_reload = auto_reload
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
742 self._cache = {}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
743 self._mtime = {}
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
744
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
745 def load(self, filename):
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
746 """Load the template with the given name.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
747
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
748 This method searches the search path trying to locate a template
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
749 matching the given name. If no such template is found, a
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
750 `TemplateNotFound` exception is raised. Otherwise, a `Template` object
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
751 representing the requested template is returned.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
752
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
753 Template searches are cached to avoid having to parse the same template
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
754 file more than once. Thus, subsequent calls of this method with the
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
755 same template file name will return the same `Template` object.
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
756
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
757 @param filename: the relative path of the template file to load
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
758 """
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
759 filename = os.path.normpath(filename)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
760 try:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
761 tmpl = self._cache[filename]
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
762 if not self.auto_reload or \
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
763 os.path.getmtime(tmpl.filename) == self._mtime[filename]:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
764 return tmpl
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
765 except KeyError:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
766 pass
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
767 for dirname in self.search_path:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
768 filepath = os.path.join(dirname, filename)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
769 try:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
770 fileobj = file(filepath, 'rt')
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
771 try:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
772 tmpl = Template(fileobj, filename=filepath)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
773 tmpl.pre_filters.append(IncludeFilter(self))
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
774 finally:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
775 fileobj.close()
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
776 self._cache[filename] = tmpl
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
777 self._mtime[filename] = os.path.getmtime(filepath)
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
778 return tmpl
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
779 except IOError:
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
780 continue
821114ec4f69 Initial import.
cmlenz
parents:
diff changeset
781 raise TemplateNotFound(filename, self.search_path)
Copyright (C) 2012-2017 Edgewall Software