blob: 803e7a8326fd3d6b904b22a800d01c4ed3bf5051 [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
Armin Ronachere73e0972009-03-05 23:47:00 +010027# the function to create jinja traceback objects. This is dynamically
28# imported on the first exception in the exception handler.
29_make_traceback = None
30
Armin Ronacher203bfcb2008-04-24 21:54:44 +020031
Armin Ronacherb5124e62008-04-25 00:36:14 +020032def get_spontaneous_environment(*args):
Georg Brandl3e497b72008-09-19 09:55:17 +000033 """Return a new spontaneous environment. A spontaneous environment is an
34 unnamed and unaccessible (in theory) environment that is used for
35 templates generated from a string and not from the file system.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020036 """
37 try:
38 env = _spontaneous_environments.get(args)
39 except TypeError:
40 return Environment(*args)
41 if env is not None:
42 return env
43 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020044 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020045 return env
46
47
Armin Ronacher7259c762008-04-30 13:03:59 +020048def create_cache(size):
49 """Return the cache class for the given size."""
50 if size == 0:
51 return None
52 if size < 0:
53 return {}
54 return LRUCache(size)
55
56
Armin Ronacherccae0552008-10-05 23:08:58 +020057def copy_cache(cache):
58 """Create an empty copy of the given cache."""
59 if cache is None:
Armin Ronacher2bc1ef72008-12-08 15:21:26 +010060 return None
Armin Ronacherccae0552008-10-05 23:08:58 +020061 elif type(cache) is dict:
62 return {}
63 return LRUCache(cache.capacity)
64
65
Armin Ronacher7259c762008-04-30 13:03:59 +020066def load_extensions(environment, extensions):
67 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020068 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020069 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020070 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020071 for extension in extensions:
72 if isinstance(extension, basestring):
73 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020074 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020075 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020076
Armin Ronacher203bfcb2008-04-24 21:54:44 +020077
Armin Ronacher7259c762008-04-30 13:03:59 +020078def _environment_sanity_check(environment):
79 """Perform a sanity check on the environment."""
80 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
81 'be a subclass of undefined because filters depend on it.'
82 assert environment.block_start_string != \
83 environment.variable_start_string != \
84 environment.comment_start_string, 'block, variable and comment ' \
85 'start strings must be different'
Armin Ronacherf3c35c42008-05-23 23:18:14 +020086 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
87 'newline_sequence set to unknown line ending string.'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020088 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020089
90
Armin Ronacher07bc6842008-03-31 14:18:49 +020091class Environment(object):
Armin Ronacherf3c35c42008-05-23 23:18:14 +020092 r"""The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020093 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020094 globals and others. Instances of this class may be modified if
95 they are not shared and if no template was loaded so far.
96 Modifications on environments after the first template was loaded
97 will lead to surprising effects and undefined behavior.
98
99 Here the possible initialization parameters:
100
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200101 `block_start_string`
102 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200103
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200104 `block_end_string`
105 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200106
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200107 `variable_start_string`
108 The string marking the begin of a print statement.
109 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +0200110
Armin Ronacher63fd7982008-06-20 18:47:56 +0200111 `variable_end_string`
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200112 The string marking the end of a print statement. Defaults to
113 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200114
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200115 `comment_start_string`
116 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200117
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200118 `comment_end_string`
119 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200120
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200121 `line_statement_prefix`
122 If given and a string, this will be used as prefix for line based
123 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200124
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200125 `trim_blocks`
126 If this is set to ``True`` the first newline after a block is
127 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200128
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200129 `newline_sequence`
130 The sequence that starts a newline. Must be one of ``'\r'``,
131 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
132 useful default for Linux and OS X systems as well as web
133 applications.
134
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200135 `extensions`
136 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200137 as strings or extension classes. For more information have a
138 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200139
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200140 `optimized`
141 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200142
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200143 `undefined`
144 :class:`Undefined` or a subclass of it that is used to represent
145 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200146
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200147 `finalize`
148 A callable that finalizes the variable. Per default no finalizing
149 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200150
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200151 `autoescape`
152 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200153 For more details about auto escaping see
154 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200155
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200156 `loader`
157 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200158
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200159 `cache_size`
160 The size of the cache. Per default this is ``50`` which means
161 that if more than 50 templates are loaded the loader will clean
162 out the least recently used template. If the cache size is set to
163 ``0`` templates are recompiled all the time, if the cache size is
164 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200165
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200166 `auto_reload`
167 Some loaders load templates from locations where the template
168 sources may change (ie: file system or database). If
169 `auto_reload` is set to `True` (default) every time a template is
170 requested the loader checks if the source changed and if yes, it
171 will reload the template. For higher performance it's possible to
172 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200173
174 `bytecode_cache`
175 If set to a bytecode cache object, this object will provide a
176 cache for the internal Jinja bytecode so that templates don't
177 have to be parsed if they were not changed.
Armin Ronachera816bf42008-09-17 21:28:01 +0200178
179 See :ref:`bytecode-cache` for more information.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200180 """
181
Armin Ronacherc63243e2008-04-14 22:53:58 +0200182 #: if this environment is sandboxed. Modifying this variable won't make
183 #: the environment sandboxed though. For a real sandboxed environment
184 #: have a look at jinja2.sandbox
185 sandboxed = False
186
Armin Ronacher7259c762008-04-30 13:03:59 +0200187 #: True if the environment is just an overlay
188 overlay = False
189
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200190 #: the environment this environment is linked to if it is an overlay
191 linked_to = None
192
Armin Ronacherc9705c22008-04-27 21:28:03 +0200193 #: shared environments have this set to `True`. A shared environment
194 #: must not be modified
195 shared = False
196
Armin Ronachere73e0972009-03-05 23:47:00 +0100197 exception_handler = None
198 exception_formatter = None
199
Armin Ronacher07bc6842008-03-31 14:18:49 +0200200 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200201 block_start_string=BLOCK_START_STRING,
202 block_end_string=BLOCK_END_STRING,
203 variable_start_string=VARIABLE_START_STRING,
204 variable_end_string=VARIABLE_END_STRING,
205 comment_start_string=COMMENT_START_STRING,
206 comment_end_string=COMMENT_END_STRING,
207 line_statement_prefix=LINE_STATEMENT_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 Ronacher07bc6842008-03-31 14:18:49 +0200238 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200239 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200240
Armin Ronacherf59bac22008-04-20 13:11:43 +0200241 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200242 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200243 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200244 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200245 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200246
247 # defaults
248 self.filters = DEFAULT_FILTERS.copy()
249 self.tests = DEFAULT_TESTS.copy()
250 self.globals = DEFAULT_NAMESPACE.copy()
251
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200252 # set the loader provided
253 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200254 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200255 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200256 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200257 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200258
Armin Ronacherb5124e62008-04-25 00:36:14 +0200259 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200260 self.extensions = load_extensions(self, extensions)
261
262 _environment_sanity_check(self)
263
Armin Ronacher762079c2008-05-08 23:57:56 +0200264 def extend(self, **attributes):
265 """Add the items to the instance of the environment if they do not exist
266 yet. This is used by :ref:`extensions <writing-extensions>` to register
267 callbacks and configuration values without breaking inheritance.
268 """
269 for key, value in attributes.iteritems():
270 if not hasattr(self, key):
271 setattr(self, key, value)
272
Armin Ronacher7259c762008-04-30 13:03:59 +0200273 def overlay(self, block_start_string=missing, block_end_string=missing,
274 variable_start_string=missing, variable_end_string=missing,
275 comment_start_string=missing, comment_end_string=missing,
276 line_statement_prefix=missing, trim_blocks=missing,
277 extensions=missing, optimized=missing, undefined=missing,
278 finalize=missing, autoescape=missing, loader=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200279 cache_size=missing, auto_reload=missing,
280 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200281 """Create a new overlay environment that shares all the data with the
282 current environment except of cache and the overriden attributes.
283 Extensions cannot be removed for a overlayed environment. A overlayed
284 environment automatically gets all the extensions of the environment it
285 is linked to plus optional extra extensions.
286
287 Creating overlays should happen after the initial environment was set
288 up completely. Not all attributes are truly linked, some are just
289 copied over so modifications on the original environment may not shine
290 through.
291 """
292 args = dict(locals())
293 del args['self'], args['cache_size'], args['extensions']
294
295 rv = object.__new__(self.__class__)
296 rv.__dict__.update(self.__dict__)
297 rv.overlay = True
298 rv.linked_to = self
299
300 for key, value in args.iteritems():
301 if value is not missing:
302 setattr(rv, key, value)
303
304 if cache_size is not missing:
305 rv.cache = create_cache(cache_size)
Armin Ronacherccae0552008-10-05 23:08:58 +0200306 else:
307 rv.cache = copy_cache(self.cache)
Armin Ronacher7259c762008-04-30 13:03:59 +0200308
Armin Ronacher023b5e92008-05-08 11:03:10 +0200309 rv.extensions = {}
310 for key, value in self.extensions.iteritems():
311 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200312 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200313 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200314
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200315 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200316
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200317 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200318
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200319 def getitem(self, obj, argument):
320 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200321 try:
322 return obj[argument]
323 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200324 if isinstance(argument, basestring):
325 try:
326 attr = str(argument)
327 except:
328 pass
329 else:
330 try:
331 return getattr(obj, attr)
332 except AttributeError:
333 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200334 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200335
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200336 def getattr(self, obj, attribute):
337 """Get an item or attribute of an object but prefer the attribute.
338 Unlike :meth:`getitem` the attribute *must* be a bytestring.
339 """
340 try:
341 return getattr(obj, attribute)
342 except AttributeError:
343 pass
344 try:
345 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200346 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200347 return self.undefined(obj=obj, name=attribute)
348
Armin Ronacherd416a972009-02-24 22:58:00 +0100349 @internalcode
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200350 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200351 """Parse the sourcecode and return the abstract syntax tree. This
352 tree of nodes is used by the compiler to convert the template into
353 executable source- or bytecode. This is useful for debugging or to
354 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200355
356 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
357 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200358 """
Armin Ronacher67fdddf2008-05-16 09:27:51 +0200359 if isinstance(filename, unicode):
360 filename = filename.encode('utf-8')
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200361 try:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200362 return Parser(self, source, name, filename).parse()
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200363 except TemplateSyntaxError, e:
Armin Ronachere73e0972009-03-05 23:47:00 +0100364 self.handle_exception(sys.exc_info(), source_hint=source)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200365
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200366 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200367 """Lex the given sourcecode and return a generator that yields
368 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200369 This can be useful for :ref:`extension development <writing-extensions>`
370 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200371
372 This does not perform preprocessing. If you want the preprocessing
373 of the extensions to be applied you have to filter source through
374 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200375 """
Armin Ronacherccae0552008-10-05 23:08:58 +0200376 source = unicode(source)
377 try:
378 return self.lexer.tokeniter(source, name, filename)
379 except TemplateSyntaxError, e:
Armin Ronachere73e0972009-03-05 23:47:00 +0100380 self.handle_exception(sys.exc_info(), source_hint=source)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200381
382 def preprocess(self, source, name=None, filename=None):
383 """Preprocesses the source with all extensions. This is automatically
384 called for all parsing and compiling methods but *not* for :meth:`lex`
385 because there you usually only want the actual source tokenized.
386 """
387 return reduce(lambda s, e: e.preprocess(s, name, filename),
388 self.extensions.itervalues(), unicode(source))
389
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100390 def _tokenize(self, source, name, filename=None, state=None):
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200391 """Called by the parser to do the preprocessing and filtering
392 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
393 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200394 source = self.preprocess(source, name, filename)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100395 stream = self.lexer.tokenize(source, name, filename, state)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200396 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200397 stream = ext.filter_stream(stream)
398 if not isinstance(stream, TokenStream):
399 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200400 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200401
Armin Ronacherd416a972009-02-24 22:58:00 +0100402 @internalcode
Armin Ronacher981cbf62008-05-13 09:12:27 +0200403 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200404 """Compile a node or template source code. The `name` parameter is
405 the load name of the template after it was joined using
406 :meth:`join_path` if necessary, not the filename on the file system.
407 the `filename` parameter is the estimated filename of the template on
408 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200409 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200410
411 The return value of this method is a python code object. If the `raw`
412 parameter is `True` the return value will be a string with python
413 code equivalent to the bytecode returned otherwise. This method is
414 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200415 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200416 if isinstance(source, basestring):
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200417 source = self.parse(source, name, filename)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200418 if self.optimized:
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100419 source = optimize(source, self)
420 source = generate(source, self, name, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200421 if raw:
422 return source
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200423 if filename is None:
Armin Ronacher68f77672008-04-17 11:50:39 +0200424 filename = '<template>'
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200425 elif isinstance(filename, unicode):
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200426 filename = filename.encode('utf-8')
427 return compile(source, filename, 'exec')
428
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100429 def compile_expression(self, source, undefined_to_none=True):
430 """A handy helper method that returns a callable that accepts keyword
431 arguments that appear as variables in the expression. If called it
432 returns the result of the expression.
433
434 This is useful if applications want to use the same rules as Jinja
435 in template "configuration files" or similar situations.
436
437 Example usage:
438
439 >>> env = Environment()
440 >>> expr = env.compile_expression('foo == 42')
441 >>> expr(foo=23)
442 False
443 >>> expr(foo=42)
444 True
445
446 Per default the return value is converted to `None` if the
447 expression returns an undefined value. This can be changed
448 by setting `undefined_to_none` to `False`.
449
450 >>> env.compile_expression('var')() is None
451 True
452 >>> env.compile_expression('var', undefined_to_none=False)()
453 Undefined
454
455 **new in Jinja 2.1**
456 """
457 parser = Parser(self, source, state='variable')
458 try:
459 expr = parser.parse_expression()
460 if not parser.stream.eos:
461 raise TemplateSyntaxError('chunk after expression',
462 parser.stream.current.lineno,
463 None, None)
464 except TemplateSyntaxError, e:
465 e.source = source
466 raise e
467 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
468 template = self.from_string(nodes.Template(body, lineno=1))
469 return TemplateExpression(template, undefined_to_none)
470
Armin Ronachere73e0972009-03-05 23:47:00 +0100471 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
472 """Exception handling helper. This is used internally to either raise
473 rewritten exceptions or return a rendered traceback for the template.
474 """
475 global _make_traceback
476 if exc_info is None:
477 exc_info = sys.exc_info()
478 if _make_traceback is None:
479 from jinja2.debug import make_traceback as _make_traceback
480 traceback = _make_traceback(exc_info, source_hint)
481 if rendered and self.exception_formatter is not None:
482 return self.exception_formatter(traceback)
483 if self.exception_handler is not None:
484 self.exception_handler(traceback)
485 exc_type, exc_value, tb = traceback.standard_exc_info
486 raise exc_type, exc_value, tb
487
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200488 def join_path(self, template, parent):
489 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200490 relative to the loader root so this method returns the `template`
491 parameter unchanged, but if the paths should be relative to the
492 parent template, this function can be used to calculate the real
493 template name.
494
495 Subclasses may override this method and implement template path
496 joining here.
497 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200498 return template
499
Armin Ronacherd416a972009-02-24 22:58:00 +0100500 @internalcode
Armin Ronacherfed44b52008-04-13 19:42:53 +0200501 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200502 """Load a template from the loader. If a loader is configured this
503 method ask the loader for the template and returns a :class:`Template`.
504 If the `parent` parameter is not `None`, :meth:`join_path` is called
505 to get the real template name before loading.
506
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200507 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200508 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200509
510 If the template does not exist a :exc:`TemplateNotFound` exception is
511 raised.
512 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200513 if self.loader is None:
514 raise TypeError('no loader for this environment specified')
515 if parent is not None:
516 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200517
518 if self.cache is not None:
519 template = self.cache.get(name)
520 if template is not None and (not self.auto_reload or \
521 template.is_up_to_date):
522 return template
523
524 template = self.loader.load(self, name, self.make_globals(globals))
525 if self.cache is not None:
526 self.cache[name] = template
527 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200528
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200529 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200530 """Load a template from a string. This parses the source given and
531 returns a :class:`Template` object.
532 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200533 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200534 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200535 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200536
537 def make_globals(self, d):
538 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200539 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200540 return self.globals
541 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200542
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200543
544class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200545 """The central template object. This class represents a compiled template
546 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200547
Armin Ronacherd1342312008-04-28 12:20:12 +0200548 Normally the template object is generated from an :class:`Environment` but
549 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200550 instance directly using the constructor. It takes the same arguments as
551 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200552
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200553 Every template object has a few methods and members that are guaranteed
554 to exist. However it's important that a template object should be
555 considered immutable. Modifications on the object are not supported.
556
557 Template objects created from the constructor rather than an environment
558 do have an `environment` attribute that points to a temporary environment
559 that is probably shared with other templates created with the constructor
560 and compatible settings.
561
562 >>> template = Template('Hello {{ name }}!')
563 >>> template.render(name='John Doe')
564 u'Hello John Doe!'
565
566 >>> stream = template.stream(name='John Doe')
567 >>> stream.next()
568 u'Hello John Doe!'
569 >>> stream.next()
570 Traceback (most recent call last):
571 ...
572 StopIteration
573 """
574
575 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200576 block_start_string=BLOCK_START_STRING,
577 block_end_string=BLOCK_END_STRING,
578 variable_start_string=VARIABLE_START_STRING,
579 variable_end_string=VARIABLE_END_STRING,
580 comment_start_string=COMMENT_START_STRING,
581 comment_end_string=COMMENT_END_STRING,
582 line_statement_prefix=LINE_STATEMENT_PREFIX,
583 trim_blocks=TRIM_BLOCKS,
584 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200585 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200586 optimized=True,
587 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200588 finalize=None,
589 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200590 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200591 block_start_string, block_end_string, variable_start_string,
592 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200593 line_statement_prefix, trim_blocks, newline_sequence,
594 frozenset(extensions), optimized, undefined, finalize,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200595 autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200596 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200597
Armin Ronacher7259c762008-04-30 13:03:59 +0200598 @classmethod
599 def from_code(cls, environment, code, globals, uptodate=None):
600 """Creates a template object from compiled code and the globals. This
601 is used by the loaders and environment to create a template object.
602 """
603 t = object.__new__(cls)
604 namespace = {
605 'environment': environment,
606 '__jinja_template__': t
607 }
608 exec code in namespace
609 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200610 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200611 t.name = namespace['name']
612 t.filename = code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200613 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200614
Georg Brandl3e497b72008-09-19 09:55:17 +0000615 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200616 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200617 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200618
619 # debug and loader helpers
620 t._debug_info = namespace['debug_info']
621 t._uptodate = uptodate
622
623 return t
624
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200625 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200626 """This method accepts the same arguments as the `dict` constructor:
627 A dict, a dict subclass or some keyword arguments. If no arguments
628 are given the context will be empty. These two calls do the same::
629
630 template.render(knights='that say nih')
631 template.render({'knights': 'that say nih'})
632
633 This will return the rendered template as unicode string.
634 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200635 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200636 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200637 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200638 except:
Armin Ronachere73e0972009-03-05 23:47:00 +0100639 return self.environment.handle_exception(sys.exc_info(), True)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200640
641 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200642 """Works exactly like :meth:`generate` but returns a
643 :class:`TemplateStream`.
644 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200645 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200646
647 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200648 """For very large templates it can be useful to not render the whole
649 template at once but evaluate each statement after another and yield
650 piece for piece. This method basically does exactly that and returns
651 a generator that yields one item after another as unicode strings.
652
653 It accepts the same arguments as :meth:`render`.
654 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200655 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200656 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200657 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200658 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200659 except:
Armin Ronachere73e0972009-03-05 23:47:00 +0100660 yield self.environment.handle_exception(sys.exc_info(), True)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200661
Armin Ronacher673aa882008-10-04 18:06:57 +0200662 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200663 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200664 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200665 are added to the context. If shared is set to `True` the data
666 is passed as it to the context without adding the globals.
667
668 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200669 """
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100670 return new_context(self.environment, self.name, self.blocks,
671 vars, shared, self.globals, locals)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200672
Armin Ronacher673aa882008-10-04 18:06:57 +0200673 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200674 """This method works like the :attr:`module` attribute when called
675 without arguments but it will evaluate the template every call
676 rather then caching the template. It's also possible to provide
677 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200678 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200679 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200680 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200681
Armin Ronacherd84ec462008-04-29 13:43:16 +0200682 @property
683 def module(self):
684 """The template as module. This is used for imports in the
685 template runtime but is also useful if one wants to access
686 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200687
Armin Ronacherd84ec462008-04-29 13:43:16 +0200688 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
689 >>> unicode(t.module)
690 u'23'
691 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200692 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200693 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200694 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200695 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200696 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200697 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200698
Armin Ronacherba3757b2008-04-16 19:43:16 +0200699 def get_corresponding_lineno(self, lineno):
700 """Return the source line number of a line number in the
701 generated bytecode as they are not in sync.
702 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200703 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200704 if code_line <= lineno:
705 return template_line
706 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200707
Armin Ronacher9a822052008-04-17 18:44:07 +0200708 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200709 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200710 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200711 if self._uptodate is None:
712 return True
713 return self._uptodate()
714
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200715 @property
716 def debug_info(self):
717 """The debug info mapping."""
718 return [tuple(map(int, x.split('='))) for x in
719 self._debug_info.split('&')]
720
Armin Ronacherc63243e2008-04-14 22:53:58 +0200721 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200722 if self.name is None:
723 name = 'memory:%x' % id(self)
724 else:
725 name = repr(self.name)
726 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200727
728
Armin Ronacherd84ec462008-04-29 13:43:16 +0200729class TemplateModule(object):
730 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200731 template are available as attributes on this object. Additionally
732 converting it into an unicode- or bytestrings renders the contents.
733 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200734
735 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200736 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200737 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200738 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200739
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200740 __unicode__ = lambda x: concat(x._body_stream)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200741 __html__ = lambda x: Markup(concat(x._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200742
743 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200744 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200745
746 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200747 if self.__name__ is None:
748 name = 'memory:%x' % id(self)
749 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200750 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200751 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200752
753
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100754class TemplateExpression(object):
755 """The :meth:`jinja2.Environment.compile_expression` method returns an
756 instance of this object. It encapsulates the expression-like access
757 to the template with an expression it wraps.
758 """
759
760 def __init__(self, template, undefined_to_none):
761 self._template = template
762 self._undefined_to_none = undefined_to_none
763
764 def __call__(self, *args, **kwargs):
765 context = self._template.new_context(dict(*args, **kwargs))
766 consume(self._template.root_render_func(context))
767 rv = context.vars['result']
768 if self._undefined_to_none and isinstance(rv, Undefined):
769 rv = None
770 return rv
771
772
Armin Ronacherc63243e2008-04-14 22:53:58 +0200773class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200774 """A template stream works pretty much like an ordinary python generator
775 but it can buffer multiple items to reduce the number of total iterations.
776 Per default the output is unbuffered which means that for every unbuffered
777 instruction in the template one unicode string is yielded.
778
779 If buffering is enabled with a buffer size of 5, five items are combined
780 into a new unicode string. This is mainly useful if you are streaming
781 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200782 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200783
784 def __init__(self, gen):
785 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200786 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200787
Armin Ronacher74b51062008-06-17 11:28:59 +0200788 def dump(self, fp, encoding=None, errors='strict'):
789 """Dump the complete stream into a file or file-like object.
790 Per default unicode strings are written, if you want to encode
791 before writing specifiy an `encoding`.
792
793 Example usage::
794
795 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
796 """
797 close = False
798 if isinstance(fp, basestring):
799 fp = file(fp, 'w')
800 close = True
801 try:
802 if encoding is not None:
803 iterable = (x.encode(encoding, errors) for x in self)
804 else:
805 iterable = self
806 if hasattr(fp, 'writelines'):
807 fp.writelines(iterable)
808 else:
809 for item in iterable:
810 fp.write(item)
811 finally:
812 if close:
813 fp.close()
814
Armin Ronacherc63243e2008-04-14 22:53:58 +0200815 def disable_buffering(self):
816 """Disable the output buffering."""
817 self._next = self._gen.next
818 self.buffered = False
819
820 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200821 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200822 if size <= 1:
823 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200824
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200825 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200826 buf = []
827 c_size = 0
828 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +0200829
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200830 while 1:
831 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200832 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200833 c = next()
834 push(c)
835 if c:
836 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200837 except StopIteration:
838 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200839 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200840 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200841 del buf[:]
842 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200843
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200844 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200845 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200846
847 def __iter__(self):
848 return self
849
850 def next(self):
851 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200852
853
854# hook in default template class. if anyone reads this comment: ignore that
855# it's possible to use custom templates ;-)
856Environment.template_class = Template