Mercurial > genshi > genshi-test
annotate markup/template.py @ 63:70c805c78796
Use a more neutral gray for the background color in the diagram.
author | cmlenz |
---|---|
date | Fri, 07 Jul 2006 17:58:52 +0000 |
parents | 33c2702cf6da |
children | 5c024cf58ecb |
rev | line source |
---|---|
1 | 1 # -*- coding: utf-8 -*- |
2 # | |
3 # Copyright (C) 2006 Christopher Lenz | |
4 # All rights reserved. | |
5 # | |
6 # This software is licensed as described in the file COPYING, which | |
7 # you should have received as part of this distribution. The terms | |
27 | 8 # are also available at http://markup.cmlenz.net/wiki/License. |
1 | 9 # |
10 # This software consists of voluntary contributions made by many | |
11 # individuals. For the exact contribution history, see the revision | |
27 | 12 # history and logs, available at http://markup.cmlenz.net/log/. |
1 | 13 |
14 """Template engine that is compatible with Kid (http://kid.lesscode.org) to a | |
15 certain extent. | |
16 | |
17 Differences include: | |
18 * No generation of Python code for a template; the template is "interpreted" | |
19 * No support for <?python ?> processing instructions | |
20 * Expressions are evaluated in a more flexible manner, meaning you can use e.g. | |
21 attribute access notation to access items in a dictionary, etc | |
22 * Use of XInclude and match templates instead of Kid's py:extends/py:layout | |
23 directives | |
24 * Real (thread-safe) search path support | |
25 * No dependency on ElementTree (due to the lack of pos info) | |
26 * The original pos of parse events is kept throughout the processing | |
27 pipeline, so that errors can be tracked back to a specific line/column in | |
28 the template file | |
29 * py:match directives use (basic) XPath expressions to match against input | |
30 nodes, making match templates more powerful while keeping the syntax simple | |
31 | |
32 Todo items: | |
33 * Improved error reporting | |
34 * Support for using directives as elements and not just as attributes, reducing | |
35 the need for wrapper elements with py:strip="" | |
36 * Support for list comprehensions and generator expressions in expressions | |
37 | |
38 Random thoughts: | |
39 * Is there any need to support py:extends and/or py:layout? | |
40 * Could we generate byte code from expressions? | |
41 """ | |
42 | |
43 import compiler | |
44 import os | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
45 import posixpath |
1 | 46 import re |
47 from StringIO import StringIO | |
48 | |
18
4cbebb15a834
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
49 from markup.core import Attributes, Namespace, Stream, StreamEventKind |
1 | 50 from markup.eval import Expression |
51 from markup.input import HTML, XMLParser, XML | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
52 from markup.path import Path |
1 | 53 |
54 __all__ = ['Context', 'BadDirectiveError', 'TemplateError', | |
55 'TemplateSyntaxError', 'TemplateNotFound', 'Template', | |
56 'TemplateLoader'] | |
57 | |
58 | |
59 class TemplateError(Exception): | |
60 """Base exception class for errors related to template processing.""" | |
61 | |
62 | |
63 class TemplateSyntaxError(TemplateError): | |
64 """Exception raised when an expression in a template causes a Python syntax | |
65 error.""" | |
66 | |
67 def __init__(self, message, filename='<string>', lineno=-1, offset=-1): | |
68 if isinstance(message, SyntaxError) and message.lineno is not None: | |
69 message = str(message).replace(' (line %d)' % message.lineno, '') | |
70 TemplateError.__init__(self, message) | |
71 self.filename = filename | |
72 self.lineno = lineno | |
73 self.offset = offset | |
74 | |
75 | |
76 class BadDirectiveError(TemplateSyntaxError): | |
77 """Exception raised when an unknown directive is encountered when parsing | |
78 a template. | |
79 | |
80 An unknown directive is any attribute using the namespace for directives, | |
81 with a local name that doesn't match any registered directive. | |
82 """ | |
83 | |
84 def __init__(self, name, filename='<string>', lineno=-1): | |
85 TemplateSyntaxError.__init__(self, 'Bad directive "%s"' % name.localname, | |
86 filename, lineno) | |
87 | |
88 | |
89 class TemplateNotFound(TemplateError): | |
90 """Exception raised when a specific template file could not be found.""" | |
91 | |
92 def __init__(self, name, search_path): | |
93 TemplateError.__init__(self, 'Template "%s" not found' % name) | |
94 self.search_path = search_path | |
95 | |
96 | |
97 class Context(object): | |
98 """A container for template input data. | |
99 | |
100 A context provides a stack of scopes. Template directives such as loops can | |
101 push a new scope on the stack with data that should only be available | |
102 inside the loop. When the loop terminates, that scope can get popped off | |
103 the stack again. | |
104 | |
105 >>> ctxt = Context(one='foo', other=1) | |
106 >>> ctxt.get('one') | |
107 'foo' | |
108 >>> ctxt.get('other') | |
109 1 | |
110 >>> ctxt.push(one='frost') | |
111 >>> ctxt.get('one') | |
112 'frost' | |
113 >>> ctxt.get('other') | |
114 1 | |
115 >>> ctxt.pop() | |
116 >>> ctxt.get('one') | |
117 'foo' | |
118 """ | |
119 | |
120 def __init__(self, **data): | |
121 self.stack = [data] | |
122 | |
123 def __getitem__(self, key): | |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
124 """Get a variable's value, starting at the current context frame and |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
125 going upward. |
1 | 126 """ |
127 return self.get(key) | |
128 | |
129 def __repr__(self): | |
130 return repr(self.stack) | |
131 | |
132 def __setitem__(self, key, value): | |
133 """Set a variable in the current context.""" | |
134 self.stack[0][key] = value | |
135 | |
136 def get(self, key): | |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
137 """Get a variable's value, starting at the current context frame and |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
138 going upward. |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
139 """ |
1 | 140 for frame in self.stack: |
141 if key in frame: | |
142 return frame[key] | |
143 | |
144 def push(self, **data): | |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
145 """Push a new context frame on the stack.""" |
1 | 146 self.stack.insert(0, data) |
147 | |
148 def pop(self): | |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
149 """Pop the top-most context frame from the stack. |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
150 |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
151 If the stack is empty, an `AssertionError` is raised. |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
152 """ |
1 | 153 assert self.stack, 'Pop from empty context stack' |
154 self.stack.pop(0) | |
155 | |
156 | |
157 class Directive(object): | |
158 """Abstract base class for template directives. | |
159 | |
54 | 160 A directive is basically a callable that takes three positional arguments: |
161 `ctxt` is the template data context, `stream` is an iterable over the | |
162 events that the directive applies to, and `directives` is is a list of | |
163 other directives on the same stream that need to be applied. | |
1 | 164 |
165 Directives can be "anonymous" or "registered". Registered directives can be | |
166 applied by the template author using an XML attribute with the | |
167 corresponding name in the template. Such directives should be subclasses of | |
31 | 168 this base class that can be instantiated with the value of the directive |
169 attribute as parameter. | |
1 | 170 |
171 Anonymous directives are simply functions conforming to the protocol | |
172 described above, and can only be applied programmatically (for example by | |
173 template filters). | |
174 """ | |
175 __slots__ = ['expr'] | |
176 | |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
177 def __init__(self, value): |
1 | 178 self.expr = value and Expression(value) or None |
179 | |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
180 def __call__(self, stream, ctxt, directives): |
1 | 181 raise NotImplementedError |
182 | |
183 def __repr__(self): | |
184 expr = '' | |
185 if self.expr is not None: | |
186 expr = ' "%s"' % self.expr.source | |
187 return '<%s%s>' % (self.__class__.__name__, expr) | |
188 | |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
189 def _apply_directives(self, stream, ctxt, directives): |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
190 if directives: |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
191 stream = directives[0](iter(stream), ctxt, directives[1:]) |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
192 return stream |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
193 |
1 | 194 |
195 class AttrsDirective(Directive): | |
196 """Implementation of the `py:attrs` template directive. | |
197 | |
198 The value of the `py:attrs` attribute should be a dictionary. The keys and | |
199 values of that dictionary will be added as attributes to the element: | |
200 | |
201 >>> ctxt = Context(foo={'class': 'collapse'}) | |
61 | 202 >>> tmpl = Template('''<ul xmlns:py="http://markup.edgewall.org/"> |
1 | 203 ... <li py:attrs="foo">Bar</li> |
204 ... </ul>''') | |
205 >>> print tmpl.generate(ctxt) | |
206 <ul> | |
207 <li class="collapse">Bar</li> | |
208 </ul> | |
209 | |
210 If the value evaluates to `None` (or any other non-truth value), no | |
211 attributes are added: | |
212 | |
213 >>> ctxt = Context(foo=None) | |
214 >>> print tmpl.generate(ctxt) | |
215 <ul> | |
216 <li>Bar</li> | |
217 </ul> | |
218 """ | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
219 __slots__ = [] |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
220 |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
221 def __call__(self, stream, ctxt, directives): |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
222 def _generate(): |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
223 kind, (tag, attrib), pos = stream.next() |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
224 attrs = self.expr.evaluate(ctxt) |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
225 if attrs: |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
226 attrib = Attributes(attrib[:]) |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
227 if not isinstance(attrs, list): # assume it's a dict |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
228 attrs = attrs.items() |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
229 for name, value in attrs: |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
230 if value is None: |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
231 attrib.remove(name) |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
232 else: |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
233 attrib.set(name, unicode(value).strip()) |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
234 yield kind, (tag, attrib), pos |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
235 for event in stream: |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
236 yield event |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
237 return self._apply_directives(_generate(), ctxt, directives) |
1 | 238 |
239 | |
240 class ContentDirective(Directive): | |
241 """Implementation of the `py:content` template directive. | |
242 | |
243 This directive replaces the content of the element with the result of | |
244 evaluating the value of the `py:content` attribute: | |
245 | |
246 >>> ctxt = Context(bar='Bye') | |
61 | 247 >>> tmpl = Template('''<ul xmlns:py="http://markup.edgewall.org/"> |
1 | 248 ... <li py:content="bar">Hello</li> |
249 ... </ul>''') | |
250 >>> print tmpl.generate(ctxt) | |
251 <ul> | |
252 <li>Bye</li> | |
253 </ul> | |
254 """ | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
255 __slots__ = [] |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
256 |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
257 def __call__(self, stream, ctxt, directives): |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
258 def _generate(): |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
259 kind, data, pos = stream.next() |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
260 if kind is Stream.START: |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
261 yield kind, data, pos # emit start tag |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
262 yield Template.EXPR, self.expr, pos |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
263 previous = stream.next() |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
264 for event in stream: |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
265 previous = event |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
266 if previous is not None: |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
267 yield previous |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
268 return self._apply_directives(_generate(), ctxt, directives) |
1 | 269 |
270 | |
271 class DefDirective(Directive): | |
272 """Implementation of the `py:def` template directive. | |
273 | |
274 This directive can be used to create "Named Template Functions", which | |
275 are template snippets that are not actually output during normal | |
276 processing, but rather can be expanded from expressions in other places | |
277 in the template. | |
278 | |
279 A named template function can be used just like a normal Python function | |
280 from template expressions: | |
281 | |
282 >>> ctxt = Context(bar='Bye') | |
61 | 283 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 284 ... <p py:def="echo(greeting, name='world')" class="message"> |
285 ... ${greeting}, ${name}! | |
286 ... </p> | |
287 ... ${echo('hi', name='you')} | |
288 ... </div>''') | |
289 >>> print tmpl.generate(ctxt) | |
290 <div> | |
291 <p class="message"> | |
292 hi, you! | |
293 </p> | |
294 </div> | |
295 | |
296 >>> ctxt = Context(bar='Bye') | |
61 | 297 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 298 ... <p py:def="echo(greeting, name='world')" class="message"> |
299 ... ${greeting}, ${name}! | |
300 ... </p> | |
301 ... <div py:replace="echo('hello')"></div> | |
302 ... </div>''') | |
303 >>> print tmpl.generate(ctxt) | |
304 <div> | |
305 <p class="message"> | |
306 hello, world! | |
307 </p> | |
308 </div> | |
309 """ | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
310 __slots__ = ['name', 'args', 'defaults', 'stream', 'directives'] |
1 | 311 |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
312 def __init__(self, args): |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
313 Directive.__init__(self, None) |
1 | 314 ast = compiler.parse(args, 'eval').node |
315 self.args = [] | |
316 self.defaults = {} | |
317 if isinstance(ast, compiler.ast.CallFunc): | |
318 self.name = ast.node.name | |
319 for arg in ast.args: | |
320 if isinstance(arg, compiler.ast.Keyword): | |
321 self.args.append(arg.name) | |
322 self.defaults[arg.name] = arg.expr.value | |
323 else: | |
324 self.args.append(arg.name) | |
325 else: | |
326 self.name = ast.name | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
327 self.stream, self.directives = [], [] |
1 | 328 |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
329 def __call__(self, stream, ctxt, directives): |
1 | 330 self.stream = list(stream) |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
331 self.directives = directives |
1 | 332 ctxt[self.name] = lambda *args, **kwargs: self._exec(ctxt, *args, |
333 **kwargs) | |
334 return [] | |
335 | |
336 def _exec(self, ctxt, *args, **kwargs): | |
337 scope = {} | |
338 args = list(args) # make mutable | |
339 for name in self.args: | |
340 if args: | |
341 scope[name] = args.pop(0) | |
342 else: | |
343 scope[name] = kwargs.pop(name, self.defaults.get(name)) | |
344 ctxt.push(**scope) | |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
345 stream = self._apply_directives(self.stream, ctxt, self.directives) |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
346 for event in stream: |
1 | 347 yield event |
348 ctxt.pop() | |
349 | |
350 | |
351 class ForDirective(Directive): | |
31 | 352 """Implementation of the `py:for` template directive for repeating an |
353 element based on an iterable in the context data. | |
1 | 354 |
355 >>> ctxt = Context(items=[1, 2, 3]) | |
61 | 356 >>> tmpl = Template('''<ul xmlns:py="http://markup.edgewall.org/"> |
1 | 357 ... <li py:for="item in items">${item}</li> |
358 ... </ul>''') | |
359 >>> print tmpl.generate(ctxt) | |
360 <ul> | |
361 <li>1</li><li>2</li><li>3</li> | |
362 </ul> | |
363 """ | |
364 __slots__ = ['targets'] | |
365 | |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
366 def __init__(self, value): |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
367 targets, value = value.split(' in ', 1) |
1 | 368 self.targets = [str(name.strip()) for name in targets.split(',')] |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
369 Directive.__init__(self, value) |
1 | 370 |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
371 def __call__(self, stream, ctxt, directives): |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
372 iterable = self.expr.evaluate(ctxt) |
1 | 373 if iterable is not None: |
374 stream = list(stream) | |
375 for item in iter(iterable): | |
376 if len(self.targets) == 1: | |
377 item = [item] | |
378 scope = {} | |
379 for idx, name in enumerate(self.targets): | |
380 scope[name] = item[idx] | |
381 ctxt.push(**scope) | |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
382 for event in self._apply_directives(stream, ctxt, directives): |
1 | 383 yield event |
384 ctxt.pop() | |
385 | |
386 def __repr__(self): | |
387 return '<%s "%s in %s">' % (self.__class__.__name__, | |
388 ', '.join(self.targets), self.expr.source) | |
389 | |
390 | |
391 class IfDirective(Directive): | |
31 | 392 """Implementation of the `py:if` template directive for conditionally |
393 excluding elements from being output. | |
1 | 394 |
395 >>> ctxt = Context(foo=True, bar='Hello') | |
61 | 396 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 397 ... <b py:if="foo">${bar}</b> |
398 ... </div>''') | |
399 >>> print tmpl.generate(ctxt) | |
400 <div> | |
401 <b>Hello</b> | |
402 </div> | |
403 """ | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
404 __slots__ = [] |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
405 |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
406 def __call__(self, stream, ctxt, directives): |
1 | 407 if self.expr.evaluate(ctxt): |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
408 return self._apply_directives(stream, ctxt, directives) |
1 | 409 return [] |
410 | |
411 | |
412 class MatchDirective(Directive): | |
413 """Implementation of the `py:match` template directive. | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
414 |
61 | 415 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
416 ... <span py:match="greeting"> |
1 | 417 ... Hello ${select('@name')} |
418 ... </span> | |
419 ... <greeting name="Dude" /> | |
420 ... </div>''') | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
421 >>> print tmpl.generate() |
1 | 422 <div> |
423 <span> | |
424 Hello Dude | |
425 </span> | |
426 </div> | |
427 """ | |
428 __slots__ = ['path', 'stream'] | |
429 | |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
430 def __init__(self, value): |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
431 Directive.__init__(self, None) |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
432 self.path = Path(value) |
1 | 433 self.stream = [] |
434 | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
435 def __call__(self, stream, ctxt, directives): |
1 | 436 self.stream = list(stream) |
38
fec9f4897415
Fix for #2 (incorrect context node in path expressions). Still some paths that produce incorrect results, but the common case seems to work now.
cmlenz
parents:
37
diff
changeset
|
437 ctxt._match_templates.append((self.path.test(ignore_context=True), |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
438 self.path, self.stream, directives)) |
1 | 439 return [] |
440 | |
441 def __repr__(self): | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
442 return '<%s "%s">' % (self.__class__.__name__, self.path.source) |
1 | 443 |
444 | |
445 class ReplaceDirective(Directive): | |
446 """Implementation of the `py:replace` template directive. | |
447 | |
31 | 448 This directive replaces the element with the result of evaluating the |
449 value of the `py:replace` attribute: | |
450 | |
1 | 451 >>> ctxt = Context(bar='Bye') |
61 | 452 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 453 ... <span py:replace="bar">Hello</span> |
454 ... </div>''') | |
455 >>> print tmpl.generate(ctxt) | |
456 <div> | |
457 Bye | |
458 </div> | |
459 | |
460 This directive is equivalent to `py:content` combined with `py:strip`, | |
461 providing a less verbose way to achieve the same effect: | |
462 | |
463 >>> ctxt = Context(bar='Bye') | |
61 | 464 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 465 ... <span py:content="bar" py:strip="">Hello</span> |
466 ... </div>''') | |
467 >>> print tmpl.generate(ctxt) | |
468 <div> | |
469 Bye | |
470 </div> | |
471 """ | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
472 __slots__ = [] |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
473 |
54 | 474 def __call__(self, stream, ctxt, directives): |
1 | 475 kind, data, pos = stream.next() |
10
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
6
diff
changeset
|
476 yield Template.EXPR, self.expr, pos |
1 | 477 |
478 | |
479 class StripDirective(Directive): | |
480 """Implementation of the `py:strip` template directive. | |
481 | |
482 When the value of the `py:strip` attribute evaluates to `True`, the element | |
483 is stripped from the output | |
484 | |
61 | 485 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 486 ... <div py:strip="True"><b>foo</b></div> |
487 ... </div>''') | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
488 >>> print tmpl.generate() |
1 | 489 <div> |
490 <b>foo</b> | |
491 </div> | |
492 | |
37
224b0b41d1da
Moved some of the tests for the strip directive to a new unittest test case to not clutter up the documentation.
cmlenz
parents:
36
diff
changeset
|
493 Leaving the attribute value empty is equivalent to a truth value. |
1 | 494 |
495 This directive is particulary interesting for named template functions or | |
496 match templates that do not generate a top-level element: | |
497 | |
61 | 498 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/"> |
1 | 499 ... <div py:def="echo(what)" py:strip=""> |
500 ... <b>${what}</b> | |
501 ... </div> | |
502 ... ${echo('foo')} | |
503 ... </div>''') | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
504 >>> print tmpl.generate() |
1 | 505 <div> |
506 <b>foo</b> | |
507 </div> | |
508 """ | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
509 __slots__ = [] |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
510 |
54 | 511 def __call__(self, stream, ctxt, directives): |
1 | 512 if self.expr: |
513 strip = self.expr.evaluate(ctxt) | |
514 else: | |
515 strip = True | |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
516 stream = self._apply_directives(stream, ctxt, directives) |
1 | 517 if strip: |
518 stream.next() # skip start tag | |
519 previous = stream.next() | |
520 for event in stream: | |
521 yield previous | |
522 previous = event | |
523 else: | |
524 for event in stream: | |
525 yield event | |
526 | |
527 | |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
528 class ChooseDirective(Directive): |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
529 """Implementation of the `py:choose` directive for conditionally selecting |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
530 one of several body elements to display. |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
531 |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
532 If the `py:choose` expression is empty the expressions of nested `py:when` |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
533 directives are tested for truth. The first true `py:when` body is output. |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
534 If no `py:when` directive is matched then the fallback directive |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
535 `py:otherwise` will be used. |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
536 |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
537 >>> ctxt = Context() |
61 | 538 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/" |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
539 ... py:choose=""> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
540 ... <span py:when="0 == 1">0</span> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
541 ... <span py:when="1 == 1">1</span> |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
542 ... <span py:otherwise="">2</span> |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
543 ... </div>''') |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
544 >>> print tmpl.generate(ctxt) |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
545 <div> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
546 <span>1</span> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
547 </div> |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
548 |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
549 If the `py:choose` directive contains an expression, the nested `py:when` |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
550 directives are tested for equality to the `py:choose` expression: |
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
551 |
61 | 552 >>> tmpl = Template('''<div xmlns:py="http://markup.edgewall.org/" |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
553 ... py:choose="2"> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
554 ... <span py:when="1">1</span> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
555 ... <span py:when="2">2</span> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
556 ... </div>''') |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
557 >>> print tmpl.generate(ctxt) |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
558 <div> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
559 <span>2</span> |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
560 </div> |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
561 |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
562 Behavior is undefined if a `py:choose` block contains content outside a |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
563 `py:when` or `py:otherwise` block. Behavior is also undefined if a |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
564 `py:otherwise` occurs before `py:when` blocks. |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
565 """ |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
566 __slots__ = ['matched', 'value'] |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
567 |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
568 def __call__(self, stream, ctxt, directives): |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
569 if self.expr: |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
570 self.value = self.expr.evaluate(ctxt) |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
571 self.matched = False |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
572 ctxt.push(_choose=self) |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
573 for event in self._apply_directives(stream, ctxt, directives): |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
574 yield event |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
575 ctxt.pop() |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
576 |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
577 |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
578 class WhenDirective(Directive): |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
579 """Implementation of the `py:when` directive for nesting in a parent with |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
580 the `py:choose` directive. |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
581 |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
582 See the documentation of `py:choose` for usage. |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
583 """ |
54 | 584 def __call__(self, stream, ctxt, directives): |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
585 choose = ctxt['_choose'] |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
586 if choose.matched: |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
587 return [] |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
588 value = self.expr.evaluate(ctxt) |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
589 try: |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
590 if value == choose.value: |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
591 choose.matched = True |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
592 return self._apply_directives(stream, ctxt, directives) |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
593 except AttributeError: |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
594 if value: |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
595 choose.matched = True |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
596 return self._apply_directives(stream, ctxt, directives) |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
597 return [] |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
598 |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
599 |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
600 class OtherwiseDirective(Directive): |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
601 """Implementation of the `py:otherwise` directive for nesting in a parent |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
602 with the `py:choose` directive. |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
603 |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
604 See the documentation of `py:choose` for usage. |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
605 """ |
54 | 606 def __call__(self, stream, ctxt, directives): |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
607 choose = ctxt['_choose'] |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
608 if choose.matched: |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
609 return [] |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
610 choose.matched = True |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
611 return self._apply_directives(stream, ctxt, directives) |
44
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
612 |
42bcb91bf025
implement `py:choose/when/otherwise` directives for conditionally selecting one of several blocks
mgood
parents:
38
diff
changeset
|
613 |
1 | 614 class Template(object): |
615 """Can parse a template and transform it into the corresponding output | |
616 based on context data. | |
617 """ | |
61 | 618 NAMESPACE = Namespace('http://markup.edgewall.org/') |
1 | 619 |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
620 EXPR = StreamEventKind('EXPR') # an expression |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
621 SUB = StreamEventKind('SUB') # a "subprogram" |
10
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
6
diff
changeset
|
622 |
1 | 623 directives = [('def', DefDirective), |
624 ('match', MatchDirective), | |
625 ('for', ForDirective), | |
626 ('if', IfDirective), | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
627 ('when', WhenDirective), |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
628 ('otherwise', OtherwiseDirective), |
53
60f1a556690e
* Add helper function to let directives apply any remaining directives, and use that helper consistently in every directive.
cmlenz
parents:
51
diff
changeset
|
629 ('choose', ChooseDirective), |
1 | 630 ('replace', ReplaceDirective), |
631 ('content', ContentDirective), | |
632 ('attrs', AttrsDirective), | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
633 ('strip', StripDirective)] |
1 | 634 _dir_by_name = dict(directives) |
635 _dir_order = [directive[1] for directive in directives] | |
636 | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
637 def __init__(self, source, basedir=None, filename=None): |
1 | 638 """Initialize a template from either a string or a file-like object.""" |
639 if isinstance(source, basestring): | |
640 self.source = StringIO(source) | |
641 else: | |
642 self.source = source | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
643 self.basedir = basedir |
1 | 644 self.filename = filename or '<string>' |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
645 if basedir and filename: |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
646 self.filepath = os.path.join(basedir, filename) |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
647 else: |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
648 self.filepath = '<string>' |
1 | 649 |
23
00835401c8cc
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
650 self.filters = [] |
1 | 651 self.parse() |
652 | |
653 def __repr__(self): | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
654 return '<%s "%s">' % (self.__class__.__name__, self.filename) |
1 | 655 |
656 def parse(self): | |
657 """Parse the template. | |
658 | |
659 The parsing stage parses the XML template and constructs a list of | |
660 directives that will be executed in the render stage. The input is | |
661 split up into literal output (markup that does not depend on the | |
662 context data) and actual directives (commands or variable | |
663 substitution). | |
664 """ | |
665 stream = [] # list of events of the "compiled" template | |
666 dirmap = {} # temporary mapping of directives to elements | |
667 ns_prefix = {} | |
668 depth = 0 | |
669 | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
670 for kind, data, pos in XMLParser(self.source, filename=self.filename): |
1 | 671 |
672 if kind is Stream.START_NS: | |
673 # Strip out the namespace declaration for template directives | |
674 prefix, uri = data | |
675 if uri == self.NAMESPACE: | |
676 ns_prefix[prefix] = uri | |
677 else: | |
678 stream.append((kind, data, pos)) | |
679 | |
680 elif kind is Stream.END_NS: | |
681 if data in ns_prefix: | |
682 del ns_prefix[data] | |
683 else: | |
684 stream.append((kind, data, pos)) | |
685 | |
686 elif kind is Stream.START: | |
687 # Record any directive attributes in start tags | |
688 tag, attrib = data | |
689 directives = [] | |
690 new_attrib = [] | |
691 for name, value in attrib: | |
18
4cbebb15a834
Actually make use of the `markup.core.Namespace` class, and add a couple of doctests.
cmlenz
parents:
17
diff
changeset
|
692 if name in self.NAMESPACE: |
1 | 693 cls = self._dir_by_name.get(name.localname) |
694 if cls is None: | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
695 raise BadDirectiveError(name, self.filename, pos[1]) |
1 | 696 else: |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
697 directives.append(cls(value)) |
1 | 698 else: |
699 value = list(self._interpolate(value, *pos)) | |
700 new_attrib.append((name, value)) | |
701 if directives: | |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
702 directives.sort(lambda a, b: cmp(self._dir_order.index(a.__class__), |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
703 self._dir_order.index(b.__class__))) |
1 | 704 dirmap[(depth, tag)] = (directives, len(stream)) |
705 | |
706 stream.append((kind, (tag, Attributes(new_attrib)), pos)) | |
707 depth += 1 | |
708 | |
709 elif kind is Stream.END: | |
710 depth -= 1 | |
711 stream.append((kind, data, pos)) | |
712 | |
713 # If there have have directive attributes with the corresponding | |
714 # start tag, move the events inbetween into a "subprogram" | |
715 if (depth, data) in dirmap: | |
716 directives, start_offset = dirmap.pop((depth, data)) | |
717 substream = stream[start_offset:] | |
10
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
6
diff
changeset
|
718 stream[start_offset:] = [(Template.SUB, |
1 | 719 (directives, substream), pos)] |
720 | |
721 elif kind is Stream.TEXT: | |
722 for kind, data, pos in self._interpolate(data, *pos): | |
723 stream.append((kind, data, pos)) | |
724 | |
725 else: | |
726 stream.append((kind, data, pos)) | |
727 | |
728 self.stream = stream | |
729 | |
730 _FULL_EXPR_RE = re.compile(r'(?<!\$)\$\{(.+?)\}') | |
731 _SHORT_EXPR_RE = re.compile(r'(?<!\$)\$([a-zA-Z][a-zA-Z0-9_\.]*)') | |
732 | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
733 def _interpolate(cls, text, filename=None, lineno=-1, offset=-1): |
1 | 734 """Parse the given string and extract expressions. |
735 | |
736 This method returns a list containing both literal text and `Expression` | |
737 objects. | |
14
76b5d4b189e6
The `<py:match>` directive now protects itself against simple infinite recursion (see MatchDirective), while still allowing recursion in general.
cmlenz
parents:
13
diff
changeset
|
738 |
1 | 739 @param text: the text to parse |
740 @param lineno: the line number at which the text was found (optional) | |
741 @param offset: the column number at which the text starts in the source | |
742 (optional) | |
743 """ | |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
744 patterns = [Template._FULL_EXPR_RE, Template._SHORT_EXPR_RE] |
1 | 745 def _interpolate(text): |
746 for idx, group in enumerate(patterns.pop(0).split(text)): | |
747 if idx % 2: | |
10
c5890ef863ba
Moved the template-specific stream event kinds into the template module.
cmlenz
parents:
6
diff
changeset
|
748 yield Template.EXPR, Expression(group), (lineno, offset) |
1 | 749 elif group: |
750 if patterns: | |
751 for result in _interpolate(group): | |
752 yield result | |
753 else: | |
754 yield Stream.TEXT, group.replace('$$', '$'), \ | |
23
00835401c8cc
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
755 (filename, lineno, offset) |
1 | 756 return _interpolate(text) |
757 _interpolate = classmethod(_interpolate) | |
758 | |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
759 def generate(self, ctxt=None): |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
760 """Apply the template to the given context data. |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
761 |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
762 @param ctxt: a `Context` instance containing the data for the template |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
763 @return: a markup event stream representing the result of applying |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
764 the template to the context data. |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
765 """ |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
766 if ctxt is None: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
767 ctxt = Context() |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
768 if not hasattr(ctxt, '_match_templates'): |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
769 ctxt._match_templates = [] |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
770 |
35
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
771 stream = self._flatten(self._match(self._eval(self.stream, ctxt), ctxt), |
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
772 ctxt) |
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
773 for filter_ in self.filters: |
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
774 stream = filter_(iter(stream), ctxt) |
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
775 return Stream(stream) |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
776 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
777 def _eval(self, stream, ctxt=None): |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
778 """Internal stream filter that evaluates any expressions in `START` and |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
779 `TEXT` events. |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
780 """ |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
781 for kind, data, pos in stream: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
782 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
783 if kind is Stream.START: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
784 # Attributes may still contain expressions in start tags at |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
785 # this point, so do some evaluation |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
786 tag, attrib = data |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
787 new_attrib = [] |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
788 for name, substream in attrib: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
789 if isinstance(substream, basestring): |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
790 value = substream |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
791 else: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
792 values = [] |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
793 for subkind, subdata, subpos in substream: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
794 if subkind is Template.EXPR: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
795 values.append(subdata.evaluate(ctxt)) |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
796 else: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
797 values.append(subdata) |
48
06c642ba2b08
convert the result of expressions in attributes to strings so that values like ints are output correctly
mgood
parents:
44
diff
changeset
|
798 value = [unicode(x) for x in values if x is not None] |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
799 if not value: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
800 continue |
23
00835401c8cc
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
801 new_attrib.append((name, u''.join(value))) |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
802 yield kind, (tag, Attributes(new_attrib)), pos |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
803 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
804 elif kind is Template.EXPR: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
805 result = data.evaluate(ctxt) |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
806 if result is None: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
807 continue |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
808 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
809 # First check for a string, otherwise the iterable test below |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
810 # succeeds, and the string will be chopped up into individual |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
811 # characters |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
812 if isinstance(result, basestring): |
54 | 813 yield Stream.TEXT, result, pos |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
814 else: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
815 # Test if the expression evaluated to an iterable, in which |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
816 # case we yield the individual items |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
817 try: |
35
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
818 for event in self._match(self._eval(iter(result), ctxt), |
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
819 ctxt): |
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
820 yield event |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
821 except TypeError: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
822 # Neither a string nor an iterable, so just pass it |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
823 # through |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
824 yield Stream.TEXT, unicode(result), pos |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
825 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
826 else: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
827 yield kind, data, pos |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
828 |
23
00835401c8cc
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
829 def _flatten(self, stream, ctxt=None): |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
830 """Internal stream filter that expands `SUB` events in the stream.""" |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
831 try: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
832 for kind, data, pos in stream: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
833 if kind is Template.SUB: |
35
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
834 # This event is a list of directives and a list of nested |
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
835 # events to which those directives should be applied |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
836 directives, substream = data |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
837 substream = directives[0](iter(substream), ctxt, directives[1:]) |
23
00835401c8cc
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
838 substream = self._match(self._eval(substream, ctxt), ctxt) |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
839 for event in self._flatten(substream, ctxt): |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
840 yield event |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
841 continue |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
842 else: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
843 yield kind, data, pos |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
844 except SyntaxError, err: |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
845 raise TemplateSyntaxError(err, self.filename, pos[1], |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
846 pos[2] + (err.offset or 0)) |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
847 |
36
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
848 def _match(self, stream, ctxt=None, match_templates=None): |
29
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
849 """Internal stream filter that applies any defined match templates |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
850 to the stream. |
4b6cee37ce62
* Minor simplification of template directives: they no longer get passed the template instance and the position, as no directive was actually using
cmlenz
parents:
27
diff
changeset
|
851 """ |
36
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
852 if match_templates is None: |
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
853 match_templates = ctxt._match_templates |
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
854 |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
855 for kind, data, pos in stream: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
856 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
857 # We (currently) only care about start and end events for matching |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
858 # We might care about namespace events in the future, though |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
859 if kind not in (Stream.START, Stream.END): |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
860 yield kind, data, pos |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
861 continue |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
862 |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
863 for idx, (test, path, template, directives) in \ |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
864 enumerate(match_templates): |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
865 result = test(kind, data, pos) |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
866 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
867 if result: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
868 # Consume and store all events until an end event |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
869 # corresponding to this start event is encountered |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
870 content = [(kind, data, pos)] |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
871 depth = 1 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
872 while depth > 0: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
873 event = stream.next() |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
874 if event[0] is Stream.START: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
875 depth += 1 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
876 elif event[0] is Stream.END: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
877 depth -= 1 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
878 content.append(event) |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
879 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
880 # enable the path to keep track of the stream state |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
881 test(*event) |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
882 |
23
00835401c8cc
Separate match and eval filters from the include and user-supplied filters.
cmlenz
parents:
22
diff
changeset
|
883 content = list(self._flatten(content, ctxt)) |
35
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
884 ctxt.push(select=lambda path: Stream(content).select(path)) |
36
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
885 |
50
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
886 if directives: |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
887 template = directives[0](iter(template), ctxt, |
a053ffb834cb
Fix the way multiple directives are applied to a single `SUB` in many cases by making the directives themselves responsible for applying any remaining directives.
cmlenz
parents:
48
diff
changeset
|
888 directives[1:]) |
36
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
889 template = self._match(self._eval(iter(template), ctxt), |
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
890 ctxt, match_templates[:idx] + |
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
891 match_templates[idx + 1:]) |
57d607f25484
Fix for #7: match templates no longer process their own output.
cmlenz
parents:
35
diff
changeset
|
892 for event in template: |
35
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
893 yield event |
3bc4778787c5
Simplify template processing model by removing dynamically generated `SUB` events.
cmlenz
parents:
31
diff
changeset
|
894 ctxt.pop() |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
895 |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
896 break |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
897 else: |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
898 yield kind, data, pos |
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
899 |
1 | 900 |
901 class TemplateLoader(object): | |
902 """Responsible for loading templates from files on the specified search | |
903 path. | |
904 | |
905 >>> import tempfile | |
906 >>> fd, path = tempfile.mkstemp(suffix='.html', prefix='template') | |
907 >>> os.write(fd, '<p>$var</p>') | |
908 11 | |
909 >>> os.close(fd) | |
910 | |
911 The template loader accepts a list of directory paths that are then used | |
912 when searching for template files, in the given order: | |
913 | |
914 >>> loader = TemplateLoader([os.path.dirname(path)]) | |
915 | |
916 The `load()` method first checks the template cache whether the requested | |
917 template has already been loaded. If not, it attempts to locate the | |
918 template file, and returns the corresponding `Template` object: | |
919 | |
920 >>> template = loader.load(os.path.basename(path)) | |
921 >>> isinstance(template, Template) | |
922 True | |
923 | |
924 Template instances are cached: requesting a template with the same name | |
925 results in the same instance being returned: | |
926 | |
927 >>> loader.load(os.path.basename(path)) is template | |
928 True | |
929 """ | |
930 def __init__(self, search_path=None, auto_reload=False): | |
931 """Create the template laoder. | |
932 | |
933 @param search_path: a list of absolute path names that should be | |
934 searched for template files | |
935 @param auto_reload: whether to check the last modification time of | |
936 template files, and reload them if they have changed | |
937 """ | |
938 self.search_path = search_path | |
939 if self.search_path is None: | |
940 self.search_path = [] | |
941 self.auto_reload = auto_reload | |
942 self._cache = {} | |
943 self._mtime = {} | |
944 | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
945 def load(self, filename, relative_to=None): |
1 | 946 """Load the template with the given name. |
947 | |
22
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
948 If the `filename` parameter is relative, this method searches the search |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
949 path trying to locate a template matching the given name. If the file |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
950 name is an absolute path, the search path is not bypassed. |
1 | 951 |
22
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
952 If requested template is not found, a `TemplateNotFound` exception is |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
953 raised. Otherwise, a `Template` object is returned that represents the |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
954 parsed template. |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
955 |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
956 Template instances are cached to avoid having to parse the same |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
957 template file more than once. Thus, subsequent calls of this method |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
958 with the same template file name will return the same `Template` |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
959 object (unless the `auto_reload` option is enabled and the file was |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
960 changed since the last parse.) |
1 | 961 |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
962 If the `relative_to` parameter is provided, the `filename` is |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
963 interpreted as being relative to that path. |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
964 |
1 | 965 @param filename: the relative path of the template file to load |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
966 @param relative_to: the filename of the template from which the new |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
967 template is being loaded, or `None` if the template is being loaded |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
968 directly |
1 | 969 """ |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
970 if relative_to: |
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
971 filename = posixpath.join(posixpath.dirname(relative_to), filename) |
1 | 972 filename = os.path.normpath(filename) |
22
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
973 |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
974 # First check the cache to avoid reparsing the same file |
1 | 975 try: |
976 tmpl = self._cache[filename] | |
977 if not self.auto_reload or \ | |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
978 os.path.getmtime(tmpl.filepath) == self._mtime[filename]: |
1 | 979 return tmpl |
980 except KeyError: | |
981 pass | |
22
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
982 |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
983 # Bypass the search path if the filename is absolute |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
984 search_path = self.search_path |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
985 if os.path.isabs(filename): |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
986 search_path = [os.path.dirname(filename)] |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
987 |
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
988 for dirname in search_path: |
1 | 989 filepath = os.path.join(dirname, filename) |
990 try: | |
991 fileobj = file(filepath, 'rt') | |
992 try: | |
22
31b13ddf9f53
Fix for the template engine plugin: the search path is now ignored if the requested template path is absolute.
cmlenz
parents:
21
diff
changeset
|
993 from markup.filters import IncludeFilter |
21
eca77129518a
* Include paths are now interpreted relative to the path of the including template. Closes #3.
cmlenz
parents:
18
diff
changeset
|
994 tmpl = Template(fileobj, basedir=dirname, filename=filename) |
17
ad63ad459524
Refactoring to address #6: all match templates are now processed by a single filter, which means that match templates added by included templates are properly applied. A side effect of this refactoring is that `Context` objects may not be reused across multiple template processing runs.
cmlenz
parents:
14
diff
changeset
|
995 tmpl.filters.append(IncludeFilter(self)) |
1 | 996 finally: |
997 fileobj.close() | |
998 self._cache[filename] = tmpl | |
999 self._mtime[filename] = os.path.getmtime(filepath) | |
1000 return tmpl | |
1001 except IOError: | |
1002 continue | |
1003 raise TemplateNotFound(filename, self.search_path) |