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