blob: a08aad20fe7d47aff27eb9c8afa1954816178d49 [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 Ronachera18872d2009-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 Ronacher59b6bd52009-03-30 21:00:16 +0200125 `line_comment_prefix`
126 If given and a string, this will be used as prefix for line based
127 based comments. See also :ref:`line-statements`.
128
129 .. versionadded:: 2.2
130
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200131 `trim_blocks`
132 If this is set to ``True`` the first newline after a block is
133 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200134
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200135 `newline_sequence`
136 The sequence that starts a newline. Must be one of ``'\r'``,
137 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
138 useful default for Linux and OS X systems as well as web
139 applications.
140
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200141 `extensions`
142 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200143 as strings or extension classes. For more information have a
144 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200145
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200146 `optimized`
147 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200148
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200149 `undefined`
150 :class:`Undefined` or a subclass of it that is used to represent
151 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200152
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200153 `finalize`
154 A callable that finalizes the variable. Per default no finalizing
155 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200156
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200157 `autoescape`
158 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200159 For more details about auto escaping see
160 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200161
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200162 `loader`
163 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200164
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200165 `cache_size`
166 The size of the cache. Per default this is ``50`` which means
167 that if more than 50 templates are loaded the loader will clean
168 out the least recently used template. If the cache size is set to
169 ``0`` templates are recompiled all the time, if the cache size is
170 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200171
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200172 `auto_reload`
173 Some loaders load templates from locations where the template
174 sources may change (ie: file system or database). If
175 `auto_reload` is set to `True` (default) every time a template is
176 requested the loader checks if the source changed and if yes, it
177 will reload the template. For higher performance it's possible to
178 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200179
180 `bytecode_cache`
181 If set to a bytecode cache object, this object will provide a
182 cache for the internal Jinja bytecode so that templates don't
183 have to be parsed if they were not changed.
Armin Ronachera816bf42008-09-17 21:28:01 +0200184
185 See :ref:`bytecode-cache` for more information.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200186 """
187
Armin Ronacherc63243e2008-04-14 22:53:58 +0200188 #: if this environment is sandboxed. Modifying this variable won't make
189 #: the environment sandboxed though. For a real sandboxed environment
190 #: have a look at jinja2.sandbox
191 sandboxed = False
192
Armin Ronacher7259c762008-04-30 13:03:59 +0200193 #: True if the environment is just an overlay
Armin Ronacher619eeed2009-07-09 21:55:29 +0200194 overlayed = False
Armin Ronacher7259c762008-04-30 13:03:59 +0200195
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200196 #: the environment this environment is linked to if it is an overlay
197 linked_to = None
198
Armin Ronacherc9705c22008-04-27 21:28:03 +0200199 #: shared environments have this set to `True`. A shared environment
200 #: must not be modified
201 shared = False
202
Armin Ronacher32ed6c92009-04-02 14:04:41 +0200203 #: these are currently EXPERIMENTAL undocumented features.
Armin Ronachera18872d2009-03-05 23:47:00 +0100204 exception_handler = None
205 exception_formatter = None
206
Armin Ronacher07bc6842008-03-31 14:18:49 +0200207 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200208 block_start_string=BLOCK_START_STRING,
209 block_end_string=BLOCK_END_STRING,
210 variable_start_string=VARIABLE_START_STRING,
211 variable_end_string=VARIABLE_END_STRING,
212 comment_start_string=COMMENT_START_STRING,
213 comment_end_string=COMMENT_END_STRING,
214 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200215 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200216 trim_blocks=TRIM_BLOCKS,
217 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200218 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200219 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200220 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200221 finalize=None,
222 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200223 loader=None,
224 cache_size=50,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200225 auto_reload=True,
226 bytecode_cache=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200227 # !!Important notice!!
228 # The constructor accepts quite a few arguments that should be
229 # passed by keyword rather than position. However it's important to
230 # not change the order of arguments because it's used at least
231 # internally in those cases:
232 # - spontaneus environments (i18n extension and Template)
233 # - unittests
234 # If parameter changes are required only add parameters at the end
235 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200236 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200237
238 # lexer / parser information
239 self.block_start_string = block_start_string
240 self.block_end_string = block_end_string
241 self.variable_start_string = variable_start_string
242 self.variable_end_string = variable_end_string
243 self.comment_start_string = comment_start_string
244 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200245 self.line_statement_prefix = line_statement_prefix
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200246 self.line_comment_prefix = line_comment_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200247 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200248 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200249
Armin Ronacherf59bac22008-04-20 13:11:43 +0200250 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200251 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200252 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200253 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200254 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200255
256 # defaults
257 self.filters = DEFAULT_FILTERS.copy()
258 self.tests = DEFAULT_TESTS.copy()
259 self.globals = DEFAULT_NAMESPACE.copy()
260
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200261 # set the loader provided
262 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200263 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200264 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200265 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200266 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200267
Armin Ronacherb5124e62008-04-25 00:36:14 +0200268 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200269 self.extensions = load_extensions(self, extensions)
270
271 _environment_sanity_check(self)
272
Armin Ronacher762079c2008-05-08 23:57:56 +0200273 def extend(self, **attributes):
274 """Add the items to the instance of the environment if they do not exist
275 yet. This is used by :ref:`extensions <writing-extensions>` to register
276 callbacks and configuration values without breaking inheritance.
277 """
278 for key, value in attributes.iteritems():
279 if not hasattr(self, key):
280 setattr(self, key, value)
281
Armin Ronacher7259c762008-04-30 13:03:59 +0200282 def overlay(self, block_start_string=missing, block_end_string=missing,
283 variable_start_string=missing, variable_end_string=missing,
284 comment_start_string=missing, comment_end_string=missing,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200285 line_statement_prefix=missing, line_comment_prefix=missing,
286 trim_blocks=missing, extensions=missing, optimized=missing,
287 undefined=missing, finalize=missing, autoescape=missing,
288 loader=missing, cache_size=missing, auto_reload=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200289 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200290 """Create a new overlay environment that shares all the data with the
Georg Brandl95632c42009-11-22 18:35:18 +0100291 current environment except of cache and the overridden attributes.
292 Extensions cannot be removed for an overlayed environment. An overlayed
Armin Ronacher7259c762008-04-30 13:03:59 +0200293 environment automatically gets all the extensions of the environment it
294 is linked to plus optional extra extensions.
295
296 Creating overlays should happen after the initial environment was set
297 up completely. Not all attributes are truly linked, some are just
298 copied over so modifications on the original environment may not shine
299 through.
300 """
301 args = dict(locals())
302 del args['self'], args['cache_size'], args['extensions']
303
304 rv = object.__new__(self.__class__)
305 rv.__dict__.update(self.__dict__)
Armin Ronacher619eeed2009-07-09 21:55:29 +0200306 rv.overlayed = True
Armin Ronacher7259c762008-04-30 13:03:59 +0200307 rv.linked_to = self
308
309 for key, value in args.iteritems():
310 if value is not missing:
311 setattr(rv, key, value)
312
313 if cache_size is not missing:
314 rv.cache = create_cache(cache_size)
Armin Ronacherccae0552008-10-05 23:08:58 +0200315 else:
316 rv.cache = copy_cache(self.cache)
Armin Ronacher7259c762008-04-30 13:03:59 +0200317
Armin Ronacher023b5e92008-05-08 11:03:10 +0200318 rv.extensions = {}
319 for key, value in self.extensions.iteritems():
320 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200321 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200322 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200323
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200324 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200325
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200326 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200327
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200328 def getitem(self, obj, argument):
329 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200330 try:
331 return obj[argument]
332 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200333 if isinstance(argument, basestring):
334 try:
335 attr = str(argument)
336 except:
337 pass
338 else:
339 try:
340 return getattr(obj, attr)
341 except AttributeError:
342 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200343 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200344
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200345 def getattr(self, obj, attribute):
346 """Get an item or attribute of an object but prefer the attribute.
347 Unlike :meth:`getitem` the attribute *must* be a bytestring.
348 """
349 try:
350 return getattr(obj, attribute)
351 except AttributeError:
352 pass
353 try:
354 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200355 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200356 return self.undefined(obj=obj, name=attribute)
357
Armin Ronacherd416a972009-02-24 22:58:00 +0100358 @internalcode
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200359 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200360 """Parse the sourcecode and return the abstract syntax tree. This
361 tree of nodes is used by the compiler to convert the template into
362 executable source- or bytecode. This is useful for debugging or to
363 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200364
365 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
366 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200367 """
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200368 try:
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700369 return self._parse(source, name, filename)
Armin Ronacher2a791922009-04-16 23:15:22 +0200370 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200371 exc_info = sys.exc_info()
372 self.handle_exception(exc_info, source_hint=source)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200373
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700374 def _parse(self, source, name, filename):
375 """Internal parsing function used by `parse` and `compile`."""
376 if isinstance(filename, unicode):
377 filename = filename.encode('utf-8')
378 return Parser(self, source, name, filename).parse()
379
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200380 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200381 """Lex the given sourcecode and return a generator that yields
382 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200383 This can be useful for :ref:`extension development <writing-extensions>`
384 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200385
386 This does not perform preprocessing. If you want the preprocessing
387 of the extensions to be applied you have to filter source through
388 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200389 """
Armin Ronacherccae0552008-10-05 23:08:58 +0200390 source = unicode(source)
391 try:
392 return self.lexer.tokeniter(source, name, filename)
Armin Ronacher2a791922009-04-16 23:15:22 +0200393 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200394 exc_info = sys.exc_info()
395 self.handle_exception(exc_info, source_hint=source)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200396
397 def preprocess(self, source, name=None, filename=None):
398 """Preprocesses the source with all extensions. This is automatically
399 called for all parsing and compiling methods but *not* for :meth:`lex`
400 because there you usually only want the actual source tokenized.
401 """
402 return reduce(lambda s, e: e.preprocess(s, name, filename),
403 self.extensions.itervalues(), unicode(source))
404
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100405 def _tokenize(self, source, name, filename=None, state=None):
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200406 """Called by the parser to do the preprocessing and filtering
407 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
408 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200409 source = self.preprocess(source, name, filename)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100410 stream = self.lexer.tokenize(source, name, filename, state)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200411 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200412 stream = ext.filter_stream(stream)
413 if not isinstance(stream, TokenStream):
414 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200415 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200416
Armin Ronacherd416a972009-02-24 22:58:00 +0100417 @internalcode
Armin Ronacher981cbf62008-05-13 09:12:27 +0200418 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200419 """Compile a node or template source code. The `name` parameter is
420 the load name of the template after it was joined using
421 :meth:`join_path` if necessary, not the filename on the file system.
422 the `filename` parameter is the estimated filename of the template on
423 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200424 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200425
426 The return value of this method is a python code object. If the `raw`
427 parameter is `True` the return value will be a string with python
428 code equivalent to the bytecode returned otherwise. This method is
429 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200430 """
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700431 source_hint = None
432 try:
433 if isinstance(source, basestring):
434 source_hint = source
435 source = self._parse(source, name, filename)
436 if self.optimized:
437 source = optimize(source, self)
438 source = generate(source, self, name, filename)
439 if raw:
440 return source
441 if filename is None:
442 filename = '<template>'
443 elif isinstance(filename, unicode):
444 filename = filename.encode('utf-8')
445 return compile(source, filename, 'exec')
446 except TemplateSyntaxError:
447 exc_info = sys.exc_info()
448 self.handle_exception(exc_info, source_hint=source)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200449
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100450 def compile_expression(self, source, undefined_to_none=True):
451 """A handy helper method that returns a callable that accepts keyword
452 arguments that appear as variables in the expression. If called it
453 returns the result of the expression.
454
455 This is useful if applications want to use the same rules as Jinja
456 in template "configuration files" or similar situations.
457
458 Example usage:
459
460 >>> env = Environment()
461 >>> expr = env.compile_expression('foo == 42')
462 >>> expr(foo=23)
463 False
464 >>> expr(foo=42)
465 True
466
467 Per default the return value is converted to `None` if the
468 expression returns an undefined value. This can be changed
469 by setting `undefined_to_none` to `False`.
470
471 >>> env.compile_expression('var')() is None
472 True
473 >>> env.compile_expression('var', undefined_to_none=False)()
474 Undefined
475
476 **new in Jinja 2.1**
477 """
478 parser = Parser(self, source, state='variable')
Armin Ronacherbd357722009-08-05 20:25:06 +0200479 exc_info = None
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100480 try:
481 expr = parser.parse_expression()
482 if not parser.stream.eos:
483 raise TemplateSyntaxError('chunk after expression',
484 parser.stream.current.lineno,
485 None, None)
Armin Ronacher2a791922009-04-16 23:15:22 +0200486 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200487 exc_info = sys.exc_info()
488 if exc_info is not None:
489 self.handle_exception(exc_info, source_hint=source)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100490 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
491 template = self.from_string(nodes.Template(body, lineno=1))
492 return TemplateExpression(template, undefined_to_none)
493
Armin Ronachera18872d2009-03-05 23:47:00 +0100494 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
495 """Exception handling helper. This is used internally to either raise
496 rewritten exceptions or return a rendered traceback for the template.
497 """
498 global _make_traceback
499 if exc_info is None:
500 exc_info = sys.exc_info()
Armin Ronacher32ed6c92009-04-02 14:04:41 +0200501
502 # the debugging module is imported when it's used for the first time.
503 # we're doing a lot of stuff there and for applications that do not
504 # get any exceptions in template rendering there is no need to load
505 # all of that.
Armin Ronachera18872d2009-03-05 23:47:00 +0100506 if _make_traceback is None:
507 from jinja2.debug import make_traceback as _make_traceback
508 traceback = _make_traceback(exc_info, source_hint)
509 if rendered and self.exception_formatter is not None:
510 return self.exception_formatter(traceback)
511 if self.exception_handler is not None:
512 self.exception_handler(traceback)
513 exc_type, exc_value, tb = traceback.standard_exc_info
514 raise exc_type, exc_value, tb
515
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200516 def join_path(self, template, parent):
517 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200518 relative to the loader root so this method returns the `template`
519 parameter unchanged, but if the paths should be relative to the
520 parent template, this function can be used to calculate the real
521 template name.
522
523 Subclasses may override this method and implement template path
524 joining here.
525 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200526 return template
527
Armin Ronacherd416a972009-02-24 22:58:00 +0100528 @internalcode
Armin Ronacherfed44b52008-04-13 19:42:53 +0200529 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200530 """Load a template from the loader. If a loader is configured this
531 method ask the loader for the template and returns a :class:`Template`.
532 If the `parent` parameter is not `None`, :meth:`join_path` is called
533 to get the real template name before loading.
534
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200535 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200536 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200537
538 If the template does not exist a :exc:`TemplateNotFound` exception is
539 raised.
540 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200541 if self.loader is None:
542 raise TypeError('no loader for this environment specified')
543 if parent is not None:
544 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200545
546 if self.cache is not None:
547 template = self.cache.get(name)
548 if template is not None and (not self.auto_reload or \
549 template.is_up_to_date):
550 return template
551
552 template = self.loader.load(self, name, self.make_globals(globals))
553 if self.cache is not None:
554 self.cache[name] = template
555 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200556
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200557 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200558 """Load a template from a string. This parses the source given and
559 returns a :class:`Template` object.
560 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200561 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200562 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200563 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200564
565 def make_globals(self, d):
566 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200567 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200568 return self.globals
569 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200570
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200571
572class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200573 """The central template object. This class represents a compiled template
574 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200575
Armin Ronacherd1342312008-04-28 12:20:12 +0200576 Normally the template object is generated from an :class:`Environment` but
577 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200578 instance directly using the constructor. It takes the same arguments as
579 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200580
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200581 Every template object has a few methods and members that are guaranteed
582 to exist. However it's important that a template object should be
583 considered immutable. Modifications on the object are not supported.
584
585 Template objects created from the constructor rather than an environment
586 do have an `environment` attribute that points to a temporary environment
587 that is probably shared with other templates created with the constructor
588 and compatible settings.
589
590 >>> template = Template('Hello {{ name }}!')
591 >>> template.render(name='John Doe')
592 u'Hello John Doe!'
593
594 >>> stream = template.stream(name='John Doe')
595 >>> stream.next()
596 u'Hello John Doe!'
597 >>> stream.next()
598 Traceback (most recent call last):
599 ...
600 StopIteration
601 """
602
603 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200604 block_start_string=BLOCK_START_STRING,
605 block_end_string=BLOCK_END_STRING,
606 variable_start_string=VARIABLE_START_STRING,
607 variable_end_string=VARIABLE_END_STRING,
608 comment_start_string=COMMENT_START_STRING,
609 comment_end_string=COMMENT_END_STRING,
610 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200611 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200612 trim_blocks=TRIM_BLOCKS,
613 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200614 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200615 optimized=True,
616 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200617 finalize=None,
618 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200619 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200620 block_start_string, block_end_string, variable_start_string,
621 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200622 line_statement_prefix, line_comment_prefix, trim_blocks,
623 newline_sequence, frozenset(extensions), optimized, undefined,
624 finalize, autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200625 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200626
Armin Ronacher7259c762008-04-30 13:03:59 +0200627 @classmethod
628 def from_code(cls, environment, code, globals, uptodate=None):
629 """Creates a template object from compiled code and the globals. This
630 is used by the loaders and environment to create a template object.
631 """
632 t = object.__new__(cls)
633 namespace = {
634 'environment': environment,
635 '__jinja_template__': t
636 }
637 exec code in namespace
638 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200639 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200640 t.name = namespace['name']
641 t.filename = code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200642 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200643
Georg Brandl3e497b72008-09-19 09:55:17 +0000644 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200645 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200646 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200647
648 # debug and loader helpers
649 t._debug_info = namespace['debug_info']
650 t._uptodate = uptodate
651
652 return t
653
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200654 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200655 """This method accepts the same arguments as the `dict` constructor:
656 A dict, a dict subclass or some keyword arguments. If no arguments
657 are given the context will be empty. These two calls do the same::
658
659 template.render(knights='that say nih')
660 template.render({'knights': 'that say nih'})
661
662 This will return the rendered template as unicode string.
663 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200664 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200665 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200666 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200667 except:
Armin Ronacherbd357722009-08-05 20:25:06 +0200668 exc_info = sys.exc_info()
669 return self.environment.handle_exception(exc_info, True)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200670
671 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200672 """Works exactly like :meth:`generate` but returns a
673 :class:`TemplateStream`.
674 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200675 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200676
677 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200678 """For very large templates it can be useful to not render the whole
679 template at once but evaluate each statement after another and yield
680 piece for piece. This method basically does exactly that and returns
681 a generator that yields one item after another as unicode strings.
682
683 It accepts the same arguments as :meth:`render`.
684 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200685 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200686 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200687 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200688 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200689 except:
Armin Ronacherbd357722009-08-05 20:25:06 +0200690 exc_info = sys.exc_info()
691 else:
692 return
693 yield self.environment.handle_exception(exc_info, True)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200694
Armin Ronacher673aa882008-10-04 18:06:57 +0200695 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200696 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200697 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200698 are added to the context. If shared is set to `True` the data
699 is passed as it to the context without adding the globals.
700
701 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200702 """
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100703 return new_context(self.environment, self.name, self.blocks,
704 vars, shared, self.globals, locals)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200705
Armin Ronacher673aa882008-10-04 18:06:57 +0200706 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200707 """This method works like the :attr:`module` attribute when called
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100708 without arguments but it will evaluate the template on every call
709 rather than caching it. It's also possible to provide
Armin Ronacher7ceced52008-05-03 10:15:31 +0200710 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200711 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200712 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200713 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200714
Armin Ronacherd84ec462008-04-29 13:43:16 +0200715 @property
716 def module(self):
717 """The template as module. This is used for imports in the
718 template runtime but is also useful if one wants to access
719 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200720
Armin Ronacherd84ec462008-04-29 13:43:16 +0200721 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
722 >>> unicode(t.module)
723 u'23'
724 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200725 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200726 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200727 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200728 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200729 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200730 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200731
Armin Ronacherba3757b2008-04-16 19:43:16 +0200732 def get_corresponding_lineno(self, lineno):
733 """Return the source line number of a line number in the
734 generated bytecode as they are not in sync.
735 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200736 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200737 if code_line <= lineno:
738 return template_line
739 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200740
Armin Ronacher9a822052008-04-17 18:44:07 +0200741 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200742 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200743 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200744 if self._uptodate is None:
745 return True
746 return self._uptodate()
747
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200748 @property
749 def debug_info(self):
750 """The debug info mapping."""
751 return [tuple(map(int, x.split('='))) for x in
752 self._debug_info.split('&')]
753
Armin Ronacherc63243e2008-04-14 22:53:58 +0200754 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200755 if self.name is None:
756 name = 'memory:%x' % id(self)
757 else:
758 name = repr(self.name)
759 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200760
761
Armin Ronacherd84ec462008-04-29 13:43:16 +0200762class TemplateModule(object):
763 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200764 template are available as attributes on this object. Additionally
765 converting it into an unicode- or bytestrings renders the contents.
766 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200767
768 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200769 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200770 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200771 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200772
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200773 __unicode__ = lambda x: concat(x._body_stream)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200774 __html__ = lambda x: Markup(concat(x._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200775
776 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200777 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200778
779 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200780 if self.__name__ is None:
781 name = 'memory:%x' % id(self)
782 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200783 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200784 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200785
786
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100787class TemplateExpression(object):
788 """The :meth:`jinja2.Environment.compile_expression` method returns an
789 instance of this object. It encapsulates the expression-like access
790 to the template with an expression it wraps.
791 """
792
793 def __init__(self, template, undefined_to_none):
794 self._template = template
795 self._undefined_to_none = undefined_to_none
796
797 def __call__(self, *args, **kwargs):
798 context = self._template.new_context(dict(*args, **kwargs))
799 consume(self._template.root_render_func(context))
800 rv = context.vars['result']
801 if self._undefined_to_none and isinstance(rv, Undefined):
802 rv = None
803 return rv
804
805
Armin Ronacherc63243e2008-04-14 22:53:58 +0200806class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200807 """A template stream works pretty much like an ordinary python generator
808 but it can buffer multiple items to reduce the number of total iterations.
809 Per default the output is unbuffered which means that for every unbuffered
810 instruction in the template one unicode string is yielded.
811
812 If buffering is enabled with a buffer size of 5, five items are combined
813 into a new unicode string. This is mainly useful if you are streaming
814 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200815 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200816
817 def __init__(self, gen):
818 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200819 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200820
Armin Ronacher74b51062008-06-17 11:28:59 +0200821 def dump(self, fp, encoding=None, errors='strict'):
822 """Dump the complete stream into a file or file-like object.
823 Per default unicode strings are written, if you want to encode
824 before writing specifiy an `encoding`.
825
826 Example usage::
827
828 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
829 """
830 close = False
831 if isinstance(fp, basestring):
832 fp = file(fp, 'w')
833 close = True
834 try:
835 if encoding is not None:
836 iterable = (x.encode(encoding, errors) for x in self)
837 else:
838 iterable = self
839 if hasattr(fp, 'writelines'):
840 fp.writelines(iterable)
841 else:
842 for item in iterable:
843 fp.write(item)
844 finally:
845 if close:
846 fp.close()
847
Armin Ronacherc63243e2008-04-14 22:53:58 +0200848 def disable_buffering(self):
849 """Disable the output buffering."""
850 self._next = self._gen.next
851 self.buffered = False
852
853 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200854 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200855 if size <= 1:
856 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200857
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200858 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200859 buf = []
860 c_size = 0
861 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +0200862
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200863 while 1:
864 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200865 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200866 c = next()
867 push(c)
868 if c:
869 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200870 except StopIteration:
871 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200872 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200873 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200874 del buf[:]
875 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200876
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200877 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200878 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200879
880 def __iter__(self):
881 return self
882
883 def next(self):
884 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200885
886
887# hook in default template class. if anyone reads this comment: ignore that
888# it's possible to use custom templates ;-)
889Environment.template_class = Template