blob: 23bf24b8987adeef09299b807fbb720bc2a8ba56 [file] [log] [blame]
Armin Ronacher07bc6842008-03-31 14:18:49 +02001# -*- coding: utf-8 -*-
2"""
Armin Ronacher82b3f3d2008-03-31 20:01:08 +02003 jinja2.environment
4 ~~~~~~~~~~~~~~~~~~
Armin Ronacher07bc6842008-03-31 14:18:49 +02005
6 Provides a class that holds runtime and parsing time options.
7
Armin Ronacher62ccd1b2009-01-04 14:26:19 +01008 :copyright: (c) 2009 by the Jinja Team.
Armin Ronacher07bc6842008-03-31 14:18:49 +02009 :license: BSD, see LICENSE for more details.
10"""
Armin Ronacherba3757b2008-04-16 19:43:16 +020011import sys
Armin Ronacherba6e25a2008-11-02 15:58:14 +010012from jinja2 import nodes
Armin Ronacher7259c762008-04-30 13:03:59 +020013from jinja2.defaults import *
Armin Ronacher9a0078d2008-08-13 18:24:17 +020014from jinja2.lexer import get_lexer, TokenStream
Armin Ronacher05530932008-04-20 13:27:49 +020015from jinja2.parser import Parser
Armin Ronacherbcb7c532008-04-11 16:30:34 +020016from jinja2.optimizer import optimize
17from jinja2.compiler import generate
Armin Ronacher74a0cd92009-02-19 15:56:53 +010018from jinja2.runtime import Undefined, new_context
Armin Ronacheraaf010d2008-05-01 13:14:30 +020019from jinja2.exceptions import TemplateSyntaxError
Armin Ronacherba6e25a2008-11-02 15:58:14 +010020from jinja2.utils import import_string, LRUCache, Markup, missing, \
Armin Ronacherd416a972009-02-24 22:58:00 +010021 concat, consume, internalcode
Armin Ronacher07bc6842008-03-31 14:18:49 +020022
23
Armin Ronacher203bfcb2008-04-24 21:54:44 +020024# for direct template usage we have up to ten living environments
25_spontaneous_environments = LRUCache(10)
26
27
Armin Ronacherb5124e62008-04-25 00:36:14 +020028def get_spontaneous_environment(*args):
Georg Brandl3e497b72008-09-19 09:55:17 +000029 """Return a new spontaneous environment. A spontaneous environment is an
30 unnamed and unaccessible (in theory) environment that is used for
31 templates generated from a string and not from the file system.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020032 """
33 try:
34 env = _spontaneous_environments.get(args)
35 except TypeError:
36 return Environment(*args)
37 if env is not None:
38 return env
39 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020040 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020041 return env
42
43
Armin Ronacher7259c762008-04-30 13:03:59 +020044def create_cache(size):
45 """Return the cache class for the given size."""
46 if size == 0:
47 return None
48 if size < 0:
49 return {}
50 return LRUCache(size)
51
52
Armin Ronacherccae0552008-10-05 23:08:58 +020053def copy_cache(cache):
54 """Create an empty copy of the given cache."""
55 if cache is None:
Armin Ronacher2bc1ef72008-12-08 15:21:26 +010056 return None
Armin Ronacherccae0552008-10-05 23:08:58 +020057 elif type(cache) is dict:
58 return {}
59 return LRUCache(cache.capacity)
60
61
Armin Ronacher7259c762008-04-30 13:03:59 +020062def load_extensions(environment, extensions):
63 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020064 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020065 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020066 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020067 for extension in extensions:
68 if isinstance(extension, basestring):
69 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020070 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020071 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020072
Armin Ronacher203bfcb2008-04-24 21:54:44 +020073
Armin Ronacher7259c762008-04-30 13:03:59 +020074def _environment_sanity_check(environment):
75 """Perform a sanity check on the environment."""
76 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
77 'be a subclass of undefined because filters depend on it.'
78 assert environment.block_start_string != \
79 environment.variable_start_string != \
80 environment.comment_start_string, 'block, variable and comment ' \
81 'start strings must be different'
Armin Ronacherf3c35c42008-05-23 23:18:14 +020082 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
83 'newline_sequence set to unknown line ending string.'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020084 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020085
86
Armin Ronacher07bc6842008-03-31 14:18:49 +020087class Environment(object):
Armin Ronacherf3c35c42008-05-23 23:18:14 +020088 r"""The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020089 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020090 globals and others. Instances of this class may be modified if
91 they are not shared and if no template was loaded so far.
92 Modifications on environments after the first template was loaded
93 will lead to surprising effects and undefined behavior.
94
95 Here the possible initialization parameters:
96
Armin Ronacher7b5680c2008-05-06 16:54:22 +020097 `block_start_string`
98 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020099
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200100 `block_end_string`
101 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200102
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200103 `variable_start_string`
104 The string marking the begin of a print statement.
105 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +0200106
Armin Ronacher63fd7982008-06-20 18:47:56 +0200107 `variable_end_string`
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200108 The string marking the end of a print statement. Defaults to
109 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200110
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200111 `comment_start_string`
112 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200113
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200114 `comment_end_string`
115 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200116
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200117 `line_statement_prefix`
118 If given and a string, this will be used as prefix for line based
119 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200120
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200121 `line_comment_prefix`
122 If given and a string, this will be used as prefix for line based
123 based comments. See also :ref:`line-statements`.
124
125 .. versionadded:: 2.2
126
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200127 `trim_blocks`
128 If this is set to ``True`` the first newline after a block is
129 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200130
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200131 `newline_sequence`
132 The sequence that starts a newline. Must be one of ``'\r'``,
133 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
134 useful default for Linux and OS X systems as well as web
135 applications.
136
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200137 `extensions`
138 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200139 as strings or extension classes. For more information have a
140 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200141
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200142 `optimized`
143 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200144
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200145 `undefined`
146 :class:`Undefined` or a subclass of it that is used to represent
147 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200148
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200149 `finalize`
150 A callable that finalizes the variable. Per default no finalizing
151 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200152
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200153 `autoescape`
154 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200155 For more details about auto escaping see
156 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200157
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200158 `loader`
159 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200160
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200161 `cache_size`
162 The size of the cache. Per default this is ``50`` which means
163 that if more than 50 templates are loaded the loader will clean
164 out the least recently used template. If the cache size is set to
165 ``0`` templates are recompiled all the time, if the cache size is
166 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200167
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200168 `auto_reload`
169 Some loaders load templates from locations where the template
170 sources may change (ie: file system or database). If
171 `auto_reload` is set to `True` (default) every time a template is
172 requested the loader checks if the source changed and if yes, it
173 will reload the template. For higher performance it's possible to
174 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200175
176 `bytecode_cache`
177 If set to a bytecode cache object, this object will provide a
178 cache for the internal Jinja bytecode so that templates don't
179 have to be parsed if they were not changed.
Armin Ronachera816bf42008-09-17 21:28:01 +0200180
181 See :ref:`bytecode-cache` for more information.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200182 """
183
Armin Ronacherc63243e2008-04-14 22:53:58 +0200184 #: if this environment is sandboxed. Modifying this variable won't make
185 #: the environment sandboxed though. For a real sandboxed environment
186 #: have a look at jinja2.sandbox
187 sandboxed = False
188
Armin Ronacher7259c762008-04-30 13:03:59 +0200189 #: True if the environment is just an overlay
190 overlay = False
191
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200192 #: the environment this environment is linked to if it is an overlay
193 linked_to = None
194
Armin Ronacherc9705c22008-04-27 21:28:03 +0200195 #: shared environments have this set to `True`. A shared environment
196 #: must not be modified
197 shared = False
198
Armin Ronacher07bc6842008-03-31 14:18:49 +0200199 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200200 block_start_string=BLOCK_START_STRING,
201 block_end_string=BLOCK_END_STRING,
202 variable_start_string=VARIABLE_START_STRING,
203 variable_end_string=VARIABLE_END_STRING,
204 comment_start_string=COMMENT_START_STRING,
205 comment_end_string=COMMENT_END_STRING,
206 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200207 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200208 trim_blocks=TRIM_BLOCKS,
209 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200210 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200211 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200212 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200213 finalize=None,
214 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200215 loader=None,
216 cache_size=50,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200217 auto_reload=True,
218 bytecode_cache=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200219 # !!Important notice!!
220 # The constructor accepts quite a few arguments that should be
221 # passed by keyword rather than position. However it's important to
222 # not change the order of arguments because it's used at least
223 # internally in those cases:
224 # - spontaneus environments (i18n extension and Template)
225 # - unittests
226 # If parameter changes are required only add parameters at the end
227 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200228 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200229
230 # lexer / parser information
231 self.block_start_string = block_start_string
232 self.block_end_string = block_end_string
233 self.variable_start_string = variable_start_string
234 self.variable_end_string = variable_end_string
235 self.comment_start_string = comment_start_string
236 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200237 self.line_statement_prefix = line_statement_prefix
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200238 self.line_comment_prefix = line_comment_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200239 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200240 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200241
Armin Ronacherf59bac22008-04-20 13:11:43 +0200242 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200243 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200244 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200245 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200246 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200247
248 # defaults
249 self.filters = DEFAULT_FILTERS.copy()
250 self.tests = DEFAULT_TESTS.copy()
251 self.globals = DEFAULT_NAMESPACE.copy()
252
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200253 # set the loader provided
254 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200255 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200256 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200257 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200258 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200259
Armin Ronacherb5124e62008-04-25 00:36:14 +0200260 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200261 self.extensions = load_extensions(self, extensions)
262
263 _environment_sanity_check(self)
264
Armin Ronacher762079c2008-05-08 23:57:56 +0200265 def extend(self, **attributes):
266 """Add the items to the instance of the environment if they do not exist
267 yet. This is used by :ref:`extensions <writing-extensions>` to register
268 callbacks and configuration values without breaking inheritance.
269 """
270 for key, value in attributes.iteritems():
271 if not hasattr(self, key):
272 setattr(self, key, value)
273
Armin Ronacher7259c762008-04-30 13:03:59 +0200274 def overlay(self, block_start_string=missing, block_end_string=missing,
275 variable_start_string=missing, variable_end_string=missing,
276 comment_start_string=missing, comment_end_string=missing,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200277 line_statement_prefix=missing, line_comment_prefix=missing,
278 trim_blocks=missing, extensions=missing, optimized=missing,
279 undefined=missing, finalize=missing, autoescape=missing,
280 loader=missing, cache_size=missing, auto_reload=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200281 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200282 """Create a new overlay environment that shares all the data with the
283 current environment except of cache and the overriden attributes.
284 Extensions cannot be removed for a overlayed environment. A overlayed
285 environment automatically gets all the extensions of the environment it
286 is linked to plus optional extra extensions.
287
288 Creating overlays should happen after the initial environment was set
289 up completely. Not all attributes are truly linked, some are just
290 copied over so modifications on the original environment may not shine
291 through.
292 """
293 args = dict(locals())
294 del args['self'], args['cache_size'], args['extensions']
295
296 rv = object.__new__(self.__class__)
297 rv.__dict__.update(self.__dict__)
298 rv.overlay = True
299 rv.linked_to = self
300
301 for key, value in args.iteritems():
302 if value is not missing:
303 setattr(rv, key, value)
304
305 if cache_size is not missing:
306 rv.cache = create_cache(cache_size)
Armin Ronacherccae0552008-10-05 23:08:58 +0200307 else:
308 rv.cache = copy_cache(self.cache)
Armin Ronacher7259c762008-04-30 13:03:59 +0200309
Armin Ronacher023b5e92008-05-08 11:03:10 +0200310 rv.extensions = {}
311 for key, value in self.extensions.iteritems():
312 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200313 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200314 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200315
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200316 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200317
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200318 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200319
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200320 def getitem(self, obj, argument):
321 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200322 try:
323 return obj[argument]
324 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200325 if isinstance(argument, basestring):
326 try:
327 attr = str(argument)
328 except:
329 pass
330 else:
331 try:
332 return getattr(obj, attr)
333 except AttributeError:
334 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200335 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200336
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200337 def getattr(self, obj, attribute):
338 """Get an item or attribute of an object but prefer the attribute.
339 Unlike :meth:`getitem` the attribute *must* be a bytestring.
340 """
341 try:
342 return getattr(obj, attribute)
343 except AttributeError:
344 pass
345 try:
346 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200347 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200348 return self.undefined(obj=obj, name=attribute)
349
Armin Ronacherd416a972009-02-24 22:58:00 +0100350 @internalcode
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200351 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200352 """Parse the sourcecode and return the abstract syntax tree. This
353 tree of nodes is used by the compiler to convert the template into
354 executable source- or bytecode. This is useful for debugging or to
355 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200356
357 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
358 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200359 """
Armin Ronacher67fdddf2008-05-16 09:27:51 +0200360 if isinstance(filename, unicode):
361 filename = filename.encode('utf-8')
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200362 try:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200363 return Parser(self, source, name, filename).parse()
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200364 except TemplateSyntaxError, e:
Armin Ronacherd416a972009-02-24 22:58:00 +0100365 from jinja2.debug import translate_syntax_error
366 exc_type, exc_value, tb = translate_syntax_error(e, source)
367 raise exc_type, exc_value, tb
Armin Ronacher07bc6842008-03-31 14:18:49 +0200368
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200369 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200370 """Lex the given sourcecode and return a generator that yields
371 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200372 This can be useful for :ref:`extension development <writing-extensions>`
373 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200374
375 This does not perform preprocessing. If you want the preprocessing
376 of the extensions to be applied you have to filter source through
377 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200378 """
Armin Ronacherccae0552008-10-05 23:08:58 +0200379 source = unicode(source)
380 try:
381 return self.lexer.tokeniter(source, name, filename)
382 except TemplateSyntaxError, e:
Armin Ronacherd416a972009-02-24 22:58:00 +0100383 from jinja2.debug import translate_syntax_error
384 exc_type, exc_value, tb = translate_syntax_error(e, source)
385 raise exc_type, exc_value, tb
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200386
387 def preprocess(self, source, name=None, filename=None):
388 """Preprocesses the source with all extensions. This is automatically
389 called for all parsing and compiling methods but *not* for :meth:`lex`
390 because there you usually only want the actual source tokenized.
391 """
392 return reduce(lambda s, e: e.preprocess(s, name, filename),
393 self.extensions.itervalues(), unicode(source))
394
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100395 def _tokenize(self, source, name, filename=None, state=None):
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200396 """Called by the parser to do the preprocessing and filtering
397 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
398 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200399 source = self.preprocess(source, name, filename)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100400 stream = self.lexer.tokenize(source, name, filename, state)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200401 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200402 stream = ext.filter_stream(stream)
403 if not isinstance(stream, TokenStream):
404 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200405 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200406
Armin Ronacherd416a972009-02-24 22:58:00 +0100407 @internalcode
Armin Ronacher981cbf62008-05-13 09:12:27 +0200408 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200409 """Compile a node or template source code. The `name` parameter is
410 the load name of the template after it was joined using
411 :meth:`join_path` if necessary, not the filename on the file system.
412 the `filename` parameter is the estimated filename of the template on
413 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200414 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200415
416 The return value of this method is a python code object. If the `raw`
417 parameter is `True` the return value will be a string with python
418 code equivalent to the bytecode returned otherwise. This method is
419 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200420 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200421 if isinstance(source, basestring):
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200422 source = self.parse(source, name, filename)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200423 if self.optimized:
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100424 source = optimize(source, self)
425 source = generate(source, self, name, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200426 if raw:
427 return source
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200428 if filename is None:
Armin Ronacher68f77672008-04-17 11:50:39 +0200429 filename = '<template>'
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200430 elif isinstance(filename, unicode):
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200431 filename = filename.encode('utf-8')
432 return compile(source, filename, 'exec')
433
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100434 def compile_expression(self, source, undefined_to_none=True):
435 """A handy helper method that returns a callable that accepts keyword
436 arguments that appear as variables in the expression. If called it
437 returns the result of the expression.
438
439 This is useful if applications want to use the same rules as Jinja
440 in template "configuration files" or similar situations.
441
442 Example usage:
443
444 >>> env = Environment()
445 >>> expr = env.compile_expression('foo == 42')
446 >>> expr(foo=23)
447 False
448 >>> expr(foo=42)
449 True
450
451 Per default the return value is converted to `None` if the
452 expression returns an undefined value. This can be changed
453 by setting `undefined_to_none` to `False`.
454
455 >>> env.compile_expression('var')() is None
456 True
457 >>> env.compile_expression('var', undefined_to_none=False)()
458 Undefined
459
460 **new in Jinja 2.1**
461 """
462 parser = Parser(self, source, state='variable')
463 try:
464 expr = parser.parse_expression()
465 if not parser.stream.eos:
466 raise TemplateSyntaxError('chunk after expression',
467 parser.stream.current.lineno,
468 None, None)
469 except TemplateSyntaxError, e:
470 e.source = source
471 raise e
472 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
473 template = self.from_string(nodes.Template(body, lineno=1))
474 return TemplateExpression(template, undefined_to_none)
475
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200476 def join_path(self, template, parent):
477 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200478 relative to the loader root so this method returns the `template`
479 parameter unchanged, but if the paths should be relative to the
480 parent template, this function can be used to calculate the real
481 template name.
482
483 Subclasses may override this method and implement template path
484 joining here.
485 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200486 return template
487
Armin Ronacherd416a972009-02-24 22:58:00 +0100488 @internalcode
Armin Ronacherfed44b52008-04-13 19:42:53 +0200489 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200490 """Load a template from the loader. If a loader is configured this
491 method ask the loader for the template and returns a :class:`Template`.
492 If the `parent` parameter is not `None`, :meth:`join_path` is called
493 to get the real template name before loading.
494
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200495 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200496 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200497
498 If the template does not exist a :exc:`TemplateNotFound` exception is
499 raised.
500 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200501 if self.loader is None:
502 raise TypeError('no loader for this environment specified')
503 if parent is not None:
504 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200505
506 if self.cache is not None:
507 template = self.cache.get(name)
508 if template is not None and (not self.auto_reload or \
509 template.is_up_to_date):
510 return template
511
512 template = self.loader.load(self, name, self.make_globals(globals))
513 if self.cache is not None:
514 self.cache[name] = template
515 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200516
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200517 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200518 """Load a template from a string. This parses the source given and
519 returns a :class:`Template` object.
520 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200521 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200522 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200523 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200524
525 def make_globals(self, d):
526 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200527 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200528 return self.globals
529 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200530
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200531
532class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200533 """The central template object. This class represents a compiled template
534 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200535
Armin Ronacherd1342312008-04-28 12:20:12 +0200536 Normally the template object is generated from an :class:`Environment` but
537 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200538 instance directly using the constructor. It takes the same arguments as
539 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200540
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200541 Every template object has a few methods and members that are guaranteed
542 to exist. However it's important that a template object should be
543 considered immutable. Modifications on the object are not supported.
544
545 Template objects created from the constructor rather than an environment
546 do have an `environment` attribute that points to a temporary environment
547 that is probably shared with other templates created with the constructor
548 and compatible settings.
549
550 >>> template = Template('Hello {{ name }}!')
551 >>> template.render(name='John Doe')
552 u'Hello John Doe!'
553
554 >>> stream = template.stream(name='John Doe')
555 >>> stream.next()
556 u'Hello John Doe!'
557 >>> stream.next()
558 Traceback (most recent call last):
559 ...
560 StopIteration
561 """
562
563 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200564 block_start_string=BLOCK_START_STRING,
565 block_end_string=BLOCK_END_STRING,
566 variable_start_string=VARIABLE_START_STRING,
567 variable_end_string=VARIABLE_END_STRING,
568 comment_start_string=COMMENT_START_STRING,
569 comment_end_string=COMMENT_END_STRING,
570 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200571 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200572 trim_blocks=TRIM_BLOCKS,
573 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200574 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200575 optimized=True,
576 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200577 finalize=None,
578 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200579 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200580 block_start_string, block_end_string, variable_start_string,
581 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200582 line_statement_prefix, line_comment_prefix, trim_blocks,
583 newline_sequence, frozenset(extensions), optimized, undefined,
584 finalize, autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200585 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200586
Armin Ronacher7259c762008-04-30 13:03:59 +0200587 @classmethod
588 def from_code(cls, environment, code, globals, uptodate=None):
589 """Creates a template object from compiled code and the globals. This
590 is used by the loaders and environment to create a template object.
591 """
592 t = object.__new__(cls)
593 namespace = {
594 'environment': environment,
595 '__jinja_template__': t
596 }
597 exec code in namespace
598 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200599 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200600 t.name = namespace['name']
601 t.filename = code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200602 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200603
Georg Brandl3e497b72008-09-19 09:55:17 +0000604 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200605 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200606 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200607
608 # debug and loader helpers
609 t._debug_info = namespace['debug_info']
610 t._uptodate = uptodate
611
612 return t
613
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200614 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200615 """This method accepts the same arguments as the `dict` constructor:
616 A dict, a dict subclass or some keyword arguments. If no arguments
617 are given the context will be empty. These two calls do the same::
618
619 template.render(knights='that say nih')
620 template.render({'knights': 'that say nih'})
621
622 This will return the rendered template as unicode string.
623 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200624 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200625 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200626 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200627 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200628 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200629 exc_type, exc_value, tb = translate_exception(sys.exc_info())
630 raise exc_type, exc_value, tb
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200631
632 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200633 """Works exactly like :meth:`generate` but returns a
634 :class:`TemplateStream`.
635 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200636 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200637
638 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200639 """For very large templates it can be useful to not render the whole
640 template at once but evaluate each statement after another and yield
641 piece for piece. This method basically does exactly that and returns
642 a generator that yields one item after another as unicode strings.
643
644 It accepts the same arguments as :meth:`render`.
645 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200646 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200647 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200648 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200649 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200650 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200651 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200652 exc_type, exc_value, tb = translate_exception(sys.exc_info())
653 raise exc_type, exc_value, tb
654
Armin Ronacher673aa882008-10-04 18:06:57 +0200655 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200656 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200657 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200658 are added to the context. If shared is set to `True` the data
659 is passed as it to the context without adding the globals.
660
661 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200662 """
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100663 return new_context(self.environment, self.name, self.blocks,
664 vars, shared, self.globals, locals)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200665
Armin Ronacher673aa882008-10-04 18:06:57 +0200666 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200667 """This method works like the :attr:`module` attribute when called
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100668 without arguments but it will evaluate the template on every call
669 rather than caching it. It's also possible to provide
Armin Ronacher7ceced52008-05-03 10:15:31 +0200670 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200671 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200672 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200673 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200674
Armin Ronacherd84ec462008-04-29 13:43:16 +0200675 @property
676 def module(self):
677 """The template as module. This is used for imports in the
678 template runtime but is also useful if one wants to access
679 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200680
Armin Ronacherd84ec462008-04-29 13:43:16 +0200681 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
682 >>> unicode(t.module)
683 u'23'
684 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200685 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200686 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200687 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200688 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200689 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200690 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200691
Armin Ronacherba3757b2008-04-16 19:43:16 +0200692 def get_corresponding_lineno(self, lineno):
693 """Return the source line number of a line number in the
694 generated bytecode as they are not in sync.
695 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200696 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200697 if code_line <= lineno:
698 return template_line
699 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200700
Armin Ronacher9a822052008-04-17 18:44:07 +0200701 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200702 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200703 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200704 if self._uptodate is None:
705 return True
706 return self._uptodate()
707
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200708 @property
709 def debug_info(self):
710 """The debug info mapping."""
711 return [tuple(map(int, x.split('='))) for x in
712 self._debug_info.split('&')]
713
Armin Ronacherc63243e2008-04-14 22:53:58 +0200714 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200715 if self.name is None:
716 name = 'memory:%x' % id(self)
717 else:
718 name = repr(self.name)
719 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200720
721
Armin Ronacherd84ec462008-04-29 13:43:16 +0200722class TemplateModule(object):
723 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200724 template are available as attributes on this object. Additionally
725 converting it into an unicode- or bytestrings renders the contents.
726 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200727
728 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200729 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200730 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200731 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200732
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200733 __unicode__ = lambda x: concat(x._body_stream)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200734 __html__ = lambda x: Markup(concat(x._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200735
736 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200737 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200738
739 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200740 if self.__name__ is None:
741 name = 'memory:%x' % id(self)
742 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200743 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200744 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200745
746
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100747class TemplateExpression(object):
748 """The :meth:`jinja2.Environment.compile_expression` method returns an
749 instance of this object. It encapsulates the expression-like access
750 to the template with an expression it wraps.
751 """
752
753 def __init__(self, template, undefined_to_none):
754 self._template = template
755 self._undefined_to_none = undefined_to_none
756
757 def __call__(self, *args, **kwargs):
758 context = self._template.new_context(dict(*args, **kwargs))
759 consume(self._template.root_render_func(context))
760 rv = context.vars['result']
761 if self._undefined_to_none and isinstance(rv, Undefined):
762 rv = None
763 return rv
764
765
Armin Ronacherc63243e2008-04-14 22:53:58 +0200766class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200767 """A template stream works pretty much like an ordinary python generator
768 but it can buffer multiple items to reduce the number of total iterations.
769 Per default the output is unbuffered which means that for every unbuffered
770 instruction in the template one unicode string is yielded.
771
772 If buffering is enabled with a buffer size of 5, five items are combined
773 into a new unicode string. This is mainly useful if you are streaming
774 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200775 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200776
777 def __init__(self, gen):
778 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200779 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200780
Armin Ronacher74b51062008-06-17 11:28:59 +0200781 def dump(self, fp, encoding=None, errors='strict'):
782 """Dump the complete stream into a file or file-like object.
783 Per default unicode strings are written, if you want to encode
784 before writing specifiy an `encoding`.
785
786 Example usage::
787
788 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
789 """
790 close = False
791 if isinstance(fp, basestring):
792 fp = file(fp, 'w')
793 close = True
794 try:
795 if encoding is not None:
796 iterable = (x.encode(encoding, errors) for x in self)
797 else:
798 iterable = self
799 if hasattr(fp, 'writelines'):
800 fp.writelines(iterable)
801 else:
802 for item in iterable:
803 fp.write(item)
804 finally:
805 if close:
806 fp.close()
807
Armin Ronacherc63243e2008-04-14 22:53:58 +0200808 def disable_buffering(self):
809 """Disable the output buffering."""
810 self._next = self._gen.next
811 self.buffered = False
812
813 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200814 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200815 if size <= 1:
816 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200817
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200818 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200819 buf = []
820 c_size = 0
821 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +0200822
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200823 while 1:
824 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200825 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200826 c = next()
827 push(c)
828 if c:
829 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200830 except StopIteration:
831 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200832 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200833 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200834 del buf[:]
835 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200836
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200837 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200838 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200839
840 def __iter__(self):
841 return self
842
843 def next(self):
844 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200845
846
847# hook in default template class. if anyone reads this comment: ignore that
848# it's possible to use custom templates ;-)
849Environment.template_class = Template