blob: 8983123828ffcea25f54ae883adf48e7589864b9 [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 Ronacher55494e42010-01-22 09:41:48 +01008 :copyright: (c) 2010 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 Ronacher31bbd9e2010-01-14 00:41:30 +010019from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \
20 TemplatesNotFound
Armin Ronacherba6e25a2008-11-02 15:58:14 +010021from jinja2.utils import import_string, LRUCache, Markup, missing, \
Armin Ronacherd416a972009-02-24 22:58:00 +010022 concat, consume, internalcode
Armin Ronacher07bc6842008-03-31 14:18:49 +020023
24
Armin Ronacher203bfcb2008-04-24 21:54:44 +020025# for direct template usage we have up to ten living environments
26_spontaneous_environments = LRUCache(10)
27
Armin Ronachera18872d2009-03-05 23:47:00 +010028# the function to create jinja traceback objects. This is dynamically
29# imported on the first exception in the exception handler.
30_make_traceback = None
31
Armin Ronacher203bfcb2008-04-24 21:54:44 +020032
Armin Ronacherb5124e62008-04-25 00:36:14 +020033def get_spontaneous_environment(*args):
Georg Brandl3e497b72008-09-19 09:55:17 +000034 """Return a new spontaneous environment. A spontaneous environment is an
35 unnamed and unaccessible (in theory) environment that is used for
36 templates generated from a string and not from the file system.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020037 """
38 try:
39 env = _spontaneous_environments.get(args)
40 except TypeError:
41 return Environment(*args)
42 if env is not None:
43 return env
44 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020045 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020046 return env
47
48
Armin Ronacher7259c762008-04-30 13:03:59 +020049def create_cache(size):
50 """Return the cache class for the given size."""
51 if size == 0:
52 return None
53 if size < 0:
54 return {}
55 return LRUCache(size)
56
57
Armin Ronacherccae0552008-10-05 23:08:58 +020058def copy_cache(cache):
59 """Create an empty copy of the given cache."""
60 if cache is None:
Armin Ronacher2bc1ef72008-12-08 15:21:26 +010061 return None
Armin Ronacherccae0552008-10-05 23:08:58 +020062 elif type(cache) is dict:
63 return {}
64 return LRUCache(cache.capacity)
65
66
Armin Ronacher7259c762008-04-30 13:03:59 +020067def load_extensions(environment, extensions):
68 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020069 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020070 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020071 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020072 for extension in extensions:
73 if isinstance(extension, basestring):
74 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020075 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020076 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020077
Armin Ronacher203bfcb2008-04-24 21:54:44 +020078
Armin Ronacher7259c762008-04-30 13:03:59 +020079def _environment_sanity_check(environment):
80 """Perform a sanity check on the environment."""
81 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
82 'be a subclass of undefined because filters depend on it.'
83 assert environment.block_start_string != \
84 environment.variable_start_string != \
85 environment.comment_start_string, 'block, variable and comment ' \
86 'start strings must be different'
Armin Ronacherf3c35c42008-05-23 23:18:14 +020087 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
88 'newline_sequence set to unknown line ending string.'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020089 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020090
91
Armin Ronacher07bc6842008-03-31 14:18:49 +020092class Environment(object):
Armin Ronacherf3c35c42008-05-23 23:18:14 +020093 r"""The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020094 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020095 globals and others. Instances of this class may be modified if
96 they are not shared and if no template was loaded so far.
97 Modifications on environments after the first template was loaded
98 will lead to surprising effects and undefined behavior.
99
100 Here the possible initialization parameters:
101
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200102 `block_start_string`
103 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200104
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200105 `block_end_string`
106 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200107
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200108 `variable_start_string`
109 The string marking the begin of a print statement.
110 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +0200111
Armin Ronacher63fd7982008-06-20 18:47:56 +0200112 `variable_end_string`
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200113 The string marking the end of a print statement. Defaults to
114 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200115
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200116 `comment_start_string`
117 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200118
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200119 `comment_end_string`
120 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200121
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200122 `line_statement_prefix`
123 If given and a string, this will be used as prefix for line based
124 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200125
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200126 `line_comment_prefix`
127 If given and a string, this will be used as prefix for line based
128 based comments. See also :ref:`line-statements`.
129
130 .. versionadded:: 2.2
131
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200132 `trim_blocks`
133 If this is set to ``True`` the first newline after a block is
134 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200135
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200136 `newline_sequence`
137 The sequence that starts a newline. Must be one of ``'\r'``,
138 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
139 useful default for Linux and OS X systems as well as web
140 applications.
141
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200142 `extensions`
143 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200144 as strings or extension classes. For more information have a
145 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200146
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200147 `optimized`
148 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200149
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200150 `undefined`
151 :class:`Undefined` or a subclass of it that is used to represent
152 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200153
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200154 `finalize`
155 A callable that finalizes the variable. Per default no finalizing
156 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200157
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200158 `autoescape`
159 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200160 For more details about auto escaping see
161 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200162
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200163 `loader`
164 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200165
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200166 `cache_size`
167 The size of the cache. Per default this is ``50`` which means
168 that if more than 50 templates are loaded the loader will clean
169 out the least recently used template. If the cache size is set to
170 ``0`` templates are recompiled all the time, if the cache size is
171 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200172
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200173 `auto_reload`
174 Some loaders load templates from locations where the template
175 sources may change (ie: file system or database). If
176 `auto_reload` is set to `True` (default) every time a template is
177 requested the loader checks if the source changed and if yes, it
178 will reload the template. For higher performance it's possible to
179 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200180
181 `bytecode_cache`
182 If set to a bytecode cache object, this object will provide a
183 cache for the internal Jinja bytecode so that templates don't
184 have to be parsed if they were not changed.
Armin Ronachera816bf42008-09-17 21:28:01 +0200185
186 See :ref:`bytecode-cache` for more information.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200187 """
188
Armin Ronacherc63243e2008-04-14 22:53:58 +0200189 #: if this environment is sandboxed. Modifying this variable won't make
190 #: the environment sandboxed though. For a real sandboxed environment
191 #: have a look at jinja2.sandbox
192 sandboxed = False
193
Armin Ronacher7259c762008-04-30 13:03:59 +0200194 #: True if the environment is just an overlay
Armin Ronacher619eeed2009-07-09 21:55:29 +0200195 overlayed = False
Armin Ronacher7259c762008-04-30 13:03:59 +0200196
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200197 #: the environment this environment is linked to if it is an overlay
198 linked_to = None
199
Armin Ronacherc9705c22008-04-27 21:28:03 +0200200 #: shared environments have this set to `True`. A shared environment
201 #: must not be modified
202 shared = False
203
Armin Ronacher32ed6c92009-04-02 14:04:41 +0200204 #: these are currently EXPERIMENTAL undocumented features.
Armin Ronachera18872d2009-03-05 23:47:00 +0100205 exception_handler = None
206 exception_formatter = None
207
Armin Ronacher07bc6842008-03-31 14:18:49 +0200208 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200209 block_start_string=BLOCK_START_STRING,
210 block_end_string=BLOCK_END_STRING,
211 variable_start_string=VARIABLE_START_STRING,
212 variable_end_string=VARIABLE_END_STRING,
213 comment_start_string=COMMENT_START_STRING,
214 comment_end_string=COMMENT_END_STRING,
215 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200216 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200217 trim_blocks=TRIM_BLOCKS,
218 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200219 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200220 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200221 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200222 finalize=None,
223 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200224 loader=None,
225 cache_size=50,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200226 auto_reload=True,
227 bytecode_cache=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200228 # !!Important notice!!
229 # The constructor accepts quite a few arguments that should be
230 # passed by keyword rather than position. However it's important to
231 # not change the order of arguments because it's used at least
232 # internally in those cases:
233 # - spontaneus environments (i18n extension and Template)
234 # - unittests
235 # If parameter changes are required only add parameters at the end
236 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200237 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200238
239 # lexer / parser information
240 self.block_start_string = block_start_string
241 self.block_end_string = block_end_string
242 self.variable_start_string = variable_start_string
243 self.variable_end_string = variable_end_string
244 self.comment_start_string = comment_start_string
245 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200246 self.line_statement_prefix = line_statement_prefix
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200247 self.line_comment_prefix = line_comment_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200248 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200249 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200250
Armin Ronacherf59bac22008-04-20 13:11:43 +0200251 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200252 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200253 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200254 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200255 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200256
257 # defaults
258 self.filters = DEFAULT_FILTERS.copy()
259 self.tests = DEFAULT_TESTS.copy()
260 self.globals = DEFAULT_NAMESPACE.copy()
261
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200262 # set the loader provided
263 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200264 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200265 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200266 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200267 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200268
Armin Ronacherb5124e62008-04-25 00:36:14 +0200269 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200270 self.extensions = load_extensions(self, extensions)
271
272 _environment_sanity_check(self)
273
Armin Ronacher762079c2008-05-08 23:57:56 +0200274 def extend(self, **attributes):
275 """Add the items to the instance of the environment if they do not exist
276 yet. This is used by :ref:`extensions <writing-extensions>` to register
277 callbacks and configuration values without breaking inheritance.
278 """
279 for key, value in attributes.iteritems():
280 if not hasattr(self, key):
281 setattr(self, key, value)
282
Armin Ronacher7259c762008-04-30 13:03:59 +0200283 def overlay(self, block_start_string=missing, block_end_string=missing,
284 variable_start_string=missing, variable_end_string=missing,
285 comment_start_string=missing, comment_end_string=missing,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200286 line_statement_prefix=missing, line_comment_prefix=missing,
287 trim_blocks=missing, extensions=missing, optimized=missing,
288 undefined=missing, finalize=missing, autoescape=missing,
289 loader=missing, cache_size=missing, auto_reload=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200290 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200291 """Create a new overlay environment that shares all the data with the
Georg Brandl95632c42009-11-22 18:35:18 +0100292 current environment except of cache and the overridden attributes.
293 Extensions cannot be removed for an overlayed environment. An overlayed
Armin Ronacher7259c762008-04-30 13:03:59 +0200294 environment automatically gets all the extensions of the environment it
295 is linked to plus optional extra extensions.
296
297 Creating overlays should happen after the initial environment was set
298 up completely. Not all attributes are truly linked, some are just
299 copied over so modifications on the original environment may not shine
300 through.
301 """
302 args = dict(locals())
303 del args['self'], args['cache_size'], args['extensions']
304
305 rv = object.__new__(self.__class__)
306 rv.__dict__.update(self.__dict__)
Armin Ronacher619eeed2009-07-09 21:55:29 +0200307 rv.overlayed = True
Armin Ronacher7259c762008-04-30 13:03:59 +0200308 rv.linked_to = self
309
310 for key, value in args.iteritems():
311 if value is not missing:
312 setattr(rv, key, value)
313
314 if cache_size is not missing:
315 rv.cache = create_cache(cache_size)
Armin Ronacherccae0552008-10-05 23:08:58 +0200316 else:
317 rv.cache = copy_cache(self.cache)
Armin Ronacher7259c762008-04-30 13:03:59 +0200318
Armin Ronacher023b5e92008-05-08 11:03:10 +0200319 rv.extensions = {}
320 for key, value in self.extensions.iteritems():
321 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200322 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200323 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200324
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200325 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200326
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200327 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200328
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200329 def getitem(self, obj, argument):
330 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200331 try:
332 return obj[argument]
333 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200334 if isinstance(argument, basestring):
335 try:
336 attr = str(argument)
337 except:
338 pass
339 else:
340 try:
341 return getattr(obj, attr)
342 except AttributeError:
343 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200344 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200345
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200346 def getattr(self, obj, attribute):
347 """Get an item or attribute of an object but prefer the attribute.
348 Unlike :meth:`getitem` the attribute *must* be a bytestring.
349 """
350 try:
351 return getattr(obj, attribute)
352 except AttributeError:
353 pass
354 try:
355 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200356 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200357 return self.undefined(obj=obj, name=attribute)
358
Armin Ronacherd416a972009-02-24 22:58:00 +0100359 @internalcode
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200360 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200361 """Parse the sourcecode and return the abstract syntax tree. This
362 tree of nodes is used by the compiler to convert the template into
363 executable source- or bytecode. This is useful for debugging or to
364 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200365
366 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
367 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200368 """
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200369 try:
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700370 return self._parse(source, name, filename)
Armin Ronacher2a791922009-04-16 23:15:22 +0200371 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200372 exc_info = sys.exc_info()
373 self.handle_exception(exc_info, source_hint=source)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200374
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700375 def _parse(self, source, name, filename):
376 """Internal parsing function used by `parse` and `compile`."""
377 if isinstance(filename, unicode):
378 filename = filename.encode('utf-8')
379 return Parser(self, source, name, filename).parse()
380
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200381 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200382 """Lex the given sourcecode and return a generator that yields
383 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200384 This can be useful for :ref:`extension development <writing-extensions>`
385 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200386
387 This does not perform preprocessing. If you want the preprocessing
388 of the extensions to be applied you have to filter source through
389 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200390 """
Armin Ronacherccae0552008-10-05 23:08:58 +0200391 source = unicode(source)
392 try:
393 return self.lexer.tokeniter(source, name, filename)
Armin Ronacher2a791922009-04-16 23:15:22 +0200394 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200395 exc_info = sys.exc_info()
396 self.handle_exception(exc_info, source_hint=source)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200397
398 def preprocess(self, source, name=None, filename=None):
399 """Preprocesses the source with all extensions. This is automatically
400 called for all parsing and compiling methods but *not* for :meth:`lex`
401 because there you usually only want the actual source tokenized.
402 """
403 return reduce(lambda s, e: e.preprocess(s, name, filename),
404 self.extensions.itervalues(), unicode(source))
405
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100406 def _tokenize(self, source, name, filename=None, state=None):
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200407 """Called by the parser to do the preprocessing and filtering
408 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
409 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200410 source = self.preprocess(source, name, filename)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100411 stream = self.lexer.tokenize(source, name, filename, state)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200412 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200413 stream = ext.filter_stream(stream)
414 if not isinstance(stream, TokenStream):
415 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200416 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200417
Armin Ronacherd416a972009-02-24 22:58:00 +0100418 @internalcode
Armin Ronacher981cbf62008-05-13 09:12:27 +0200419 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200420 """Compile a node or template source code. The `name` parameter is
421 the load name of the template after it was joined using
422 :meth:`join_path` if necessary, not the filename on the file system.
423 the `filename` parameter is the estimated filename of the template on
424 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200425 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200426
427 The return value of this method is a python code object. If the `raw`
428 parameter is `True` the return value will be a string with python
429 code equivalent to the bytecode returned otherwise. This method is
430 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200431 """
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700432 source_hint = None
433 try:
434 if isinstance(source, basestring):
435 source_hint = source
436 source = self._parse(source, name, filename)
437 if self.optimized:
438 source = optimize(source, self)
439 source = generate(source, self, name, filename)
440 if raw:
441 return source
442 if filename is None:
443 filename = '<template>'
444 elif isinstance(filename, unicode):
445 filename = filename.encode('utf-8')
446 return compile(source, filename, 'exec')
447 except TemplateSyntaxError:
448 exc_info = sys.exc_info()
449 self.handle_exception(exc_info, source_hint=source)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200450
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100451 def compile_expression(self, source, undefined_to_none=True):
452 """A handy helper method that returns a callable that accepts keyword
453 arguments that appear as variables in the expression. If called it
454 returns the result of the expression.
455
456 This is useful if applications want to use the same rules as Jinja
457 in template "configuration files" or similar situations.
458
459 Example usage:
460
461 >>> env = Environment()
462 >>> expr = env.compile_expression('foo == 42')
463 >>> expr(foo=23)
464 False
465 >>> expr(foo=42)
466 True
467
468 Per default the return value is converted to `None` if the
469 expression returns an undefined value. This can be changed
470 by setting `undefined_to_none` to `False`.
471
472 >>> env.compile_expression('var')() is None
473 True
474 >>> env.compile_expression('var', undefined_to_none=False)()
475 Undefined
476
477 **new in Jinja 2.1**
478 """
479 parser = Parser(self, source, state='variable')
Armin Ronacherbd357722009-08-05 20:25:06 +0200480 exc_info = None
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100481 try:
482 expr = parser.parse_expression()
483 if not parser.stream.eos:
484 raise TemplateSyntaxError('chunk after expression',
485 parser.stream.current.lineno,
486 None, None)
Armin Ronacher2a791922009-04-16 23:15:22 +0200487 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200488 exc_info = sys.exc_info()
489 if exc_info is not None:
490 self.handle_exception(exc_info, source_hint=source)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100491 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
492 template = self.from_string(nodes.Template(body, lineno=1))
493 return TemplateExpression(template, undefined_to_none)
494
Armin Ronachera18872d2009-03-05 23:47:00 +0100495 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
496 """Exception handling helper. This is used internally to either raise
497 rewritten exceptions or return a rendered traceback for the template.
498 """
499 global _make_traceback
500 if exc_info is None:
501 exc_info = sys.exc_info()
Armin Ronacher32ed6c92009-04-02 14:04:41 +0200502
503 # the debugging module is imported when it's used for the first time.
504 # we're doing a lot of stuff there and for applications that do not
505 # get any exceptions in template rendering there is no need to load
506 # all of that.
Armin Ronachera18872d2009-03-05 23:47:00 +0100507 if _make_traceback is None:
508 from jinja2.debug import make_traceback as _make_traceback
509 traceback = _make_traceback(exc_info, source_hint)
510 if rendered and self.exception_formatter is not None:
511 return self.exception_formatter(traceback)
512 if self.exception_handler is not None:
513 self.exception_handler(traceback)
514 exc_type, exc_value, tb = traceback.standard_exc_info
515 raise exc_type, exc_value, tb
516
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200517 def join_path(self, template, parent):
518 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200519 relative to the loader root so this method returns the `template`
520 parameter unchanged, but if the paths should be relative to the
521 parent template, this function can be used to calculate the real
522 template name.
523
524 Subclasses may override this method and implement template path
525 joining here.
526 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200527 return template
528
Armin Ronacherd416a972009-02-24 22:58:00 +0100529 @internalcode
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100530 def _load_template(self, name, globals):
531 if self.loader is None:
532 raise TypeError('no loader for this environment specified')
533 if self.cache is not None:
534 template = self.cache.get(name)
535 if template is not None and (not self.auto_reload or \
536 template.is_up_to_date):
537 return template
538 template = self.loader.load(self, name, globals)
539 if self.cache is not None:
540 self.cache[name] = template
541 return template
542
543 @internalcode
Armin Ronacherfed44b52008-04-13 19:42:53 +0200544 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200545 """Load a template from the loader. If a loader is configured this
546 method ask the loader for the template and returns a :class:`Template`.
547 If the `parent` parameter is not `None`, :meth:`join_path` is called
548 to get the real template name before loading.
549
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200550 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200551 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200552
553 If the template does not exist a :exc:`TemplateNotFound` exception is
554 raised.
555 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200556 if parent is not None:
557 name = self.join_path(name, parent)
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100558 return self._load_template(name, self.make_globals(globals))
Armin Ronacher7259c762008-04-30 13:03:59 +0200559
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100560 @internalcode
561 def select_template(self, names, parent=None, globals=None):
562 """Works like :meth:`get_template` but tries a number of templates
563 before it fails. If it cannot find any of the templates, it will
564 raise a :exc:`TemplatesNotFound` exception.
Armin Ronacher7259c762008-04-30 13:03:59 +0200565
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100566 .. versionadded:: 2.2
567 """
568 if not names:
569 raise TemplatesNotFound(message=u'Tried to select from an empty list '
570 u'of templates.')
571 globals = self.make_globals(globals)
572 for name in names:
573 if parent is not None:
574 name = self.join_path(name, parent)
575 try:
576 return self._load_template(name, globals)
577 except TemplateNotFound:
578 pass
579 raise TemplatesNotFound(names)
580
581 @internalcode
582 def get_or_select_template(self, template_name_or_list,
583 parent=None, globals=None):
584 """
585 Does a typecheck and dispatches to :meth:`select_template` if an
586 iterable of template names is given, otherwise to :meth:`get_template`.
587
588 .. versionadded:: 2.2
589 """
590 if isinstance(template_name_or_list, basestring):
591 return self.get_template(template_name_or_list, parent, globals)
592 return self.select_template(template_name_or_list, parent, globals)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200593
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200594 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200595 """Load a template from a string. This parses the source given and
596 returns a :class:`Template` object.
597 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200598 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200599 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200600 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200601
602 def make_globals(self, d):
603 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200604 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200605 return self.globals
606 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200607
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200608
609class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200610 """The central template object. This class represents a compiled template
611 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200612
Armin Ronacherd1342312008-04-28 12:20:12 +0200613 Normally the template object is generated from an :class:`Environment` but
614 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200615 instance directly using the constructor. It takes the same arguments as
616 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200617
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200618 Every template object has a few methods and members that are guaranteed
619 to exist. However it's important that a template object should be
620 considered immutable. Modifications on the object are not supported.
621
622 Template objects created from the constructor rather than an environment
623 do have an `environment` attribute that points to a temporary environment
624 that is probably shared with other templates created with the constructor
625 and compatible settings.
626
627 >>> template = Template('Hello {{ name }}!')
628 >>> template.render(name='John Doe')
629 u'Hello John Doe!'
630
631 >>> stream = template.stream(name='John Doe')
632 >>> stream.next()
633 u'Hello John Doe!'
634 >>> stream.next()
635 Traceback (most recent call last):
636 ...
637 StopIteration
638 """
639
640 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200641 block_start_string=BLOCK_START_STRING,
642 block_end_string=BLOCK_END_STRING,
643 variable_start_string=VARIABLE_START_STRING,
644 variable_end_string=VARIABLE_END_STRING,
645 comment_start_string=COMMENT_START_STRING,
646 comment_end_string=COMMENT_END_STRING,
647 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200648 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200649 trim_blocks=TRIM_BLOCKS,
650 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200651 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200652 optimized=True,
653 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200654 finalize=None,
655 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200656 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200657 block_start_string, block_end_string, variable_start_string,
658 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200659 line_statement_prefix, line_comment_prefix, trim_blocks,
660 newline_sequence, frozenset(extensions), optimized, undefined,
661 finalize, autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200662 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200663
Armin Ronacher7259c762008-04-30 13:03:59 +0200664 @classmethod
665 def from_code(cls, environment, code, globals, uptodate=None):
666 """Creates a template object from compiled code and the globals. This
667 is used by the loaders and environment to create a template object.
668 """
669 t = object.__new__(cls)
670 namespace = {
671 'environment': environment,
672 '__jinja_template__': t
673 }
674 exec code in namespace
675 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200676 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200677 t.name = namespace['name']
678 t.filename = code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200679 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200680
Georg Brandl3e497b72008-09-19 09:55:17 +0000681 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200682 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200683 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200684
685 # debug and loader helpers
686 t._debug_info = namespace['debug_info']
687 t._uptodate = uptodate
688
689 return t
690
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200691 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200692 """This method accepts the same arguments as the `dict` constructor:
693 A dict, a dict subclass or some keyword arguments. If no arguments
694 are given the context will be empty. These two calls do the same::
695
696 template.render(knights='that say nih')
697 template.render({'knights': 'that say nih'})
698
699 This will return the rendered template as unicode string.
700 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200701 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200702 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200703 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200704 except:
Armin Ronacherbd357722009-08-05 20:25:06 +0200705 exc_info = sys.exc_info()
706 return self.environment.handle_exception(exc_info, True)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200707
708 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200709 """Works exactly like :meth:`generate` but returns a
710 :class:`TemplateStream`.
711 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200712 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200713
714 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200715 """For very large templates it can be useful to not render the whole
716 template at once but evaluate each statement after another and yield
717 piece for piece. This method basically does exactly that and returns
718 a generator that yields one item after another as unicode strings.
719
720 It accepts the same arguments as :meth:`render`.
721 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200722 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200723 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200724 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200725 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200726 except:
Armin Ronacherbd357722009-08-05 20:25:06 +0200727 exc_info = sys.exc_info()
728 else:
729 return
730 yield self.environment.handle_exception(exc_info, True)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200731
Armin Ronacher673aa882008-10-04 18:06:57 +0200732 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200733 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200734 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200735 are added to the context. If shared is set to `True` the data
736 is passed as it to the context without adding the globals.
737
738 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200739 """
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100740 return new_context(self.environment, self.name, self.blocks,
741 vars, shared, self.globals, locals)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200742
Armin Ronacher673aa882008-10-04 18:06:57 +0200743 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200744 """This method works like the :attr:`module` attribute when called
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100745 without arguments but it will evaluate the template on every call
746 rather than caching it. It's also possible to provide
Armin Ronacher7ceced52008-05-03 10:15:31 +0200747 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200748 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200749 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200750 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200751
Armin Ronacherd84ec462008-04-29 13:43:16 +0200752 @property
753 def module(self):
754 """The template as module. This is used for imports in the
755 template runtime but is also useful if one wants to access
756 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200757
Armin Ronacherd84ec462008-04-29 13:43:16 +0200758 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
759 >>> unicode(t.module)
760 u'23'
761 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200762 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200763 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200764 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200765 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200766 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200767 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200768
Armin Ronacherba3757b2008-04-16 19:43:16 +0200769 def get_corresponding_lineno(self, lineno):
770 """Return the source line number of a line number in the
771 generated bytecode as they are not in sync.
772 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200773 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200774 if code_line <= lineno:
775 return template_line
776 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200777
Armin Ronacher9a822052008-04-17 18:44:07 +0200778 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200779 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200780 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200781 if self._uptodate is None:
782 return True
783 return self._uptodate()
784
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200785 @property
786 def debug_info(self):
787 """The debug info mapping."""
788 return [tuple(map(int, x.split('='))) for x in
789 self._debug_info.split('&')]
790
Armin Ronacherc63243e2008-04-14 22:53:58 +0200791 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200792 if self.name is None:
793 name = 'memory:%x' % id(self)
794 else:
795 name = repr(self.name)
796 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200797
798
Armin Ronacherd84ec462008-04-29 13:43:16 +0200799class TemplateModule(object):
800 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200801 template are available as attributes on this object. Additionally
802 converting it into an unicode- or bytestrings renders the contents.
803 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200804
805 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200806 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200807 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200808 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200809
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200810 __unicode__ = lambda x: concat(x._body_stream)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200811 __html__ = lambda x: Markup(concat(x._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200812
813 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200814 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200815
816 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200817 if self.__name__ is None:
818 name = 'memory:%x' % id(self)
819 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200820 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200821 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200822
823
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100824class TemplateExpression(object):
825 """The :meth:`jinja2.Environment.compile_expression` method returns an
826 instance of this object. It encapsulates the expression-like access
827 to the template with an expression it wraps.
828 """
829
830 def __init__(self, template, undefined_to_none):
831 self._template = template
832 self._undefined_to_none = undefined_to_none
833
834 def __call__(self, *args, **kwargs):
835 context = self._template.new_context(dict(*args, **kwargs))
836 consume(self._template.root_render_func(context))
837 rv = context.vars['result']
838 if self._undefined_to_none and isinstance(rv, Undefined):
839 rv = None
840 return rv
841
842
Armin Ronacherc63243e2008-04-14 22:53:58 +0200843class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200844 """A template stream works pretty much like an ordinary python generator
845 but it can buffer multiple items to reduce the number of total iterations.
846 Per default the output is unbuffered which means that for every unbuffered
847 instruction in the template one unicode string is yielded.
848
849 If buffering is enabled with a buffer size of 5, five items are combined
850 into a new unicode string. This is mainly useful if you are streaming
851 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200852 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200853
854 def __init__(self, gen):
855 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200856 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200857
Armin Ronacher74b51062008-06-17 11:28:59 +0200858 def dump(self, fp, encoding=None, errors='strict'):
859 """Dump the complete stream into a file or file-like object.
860 Per default unicode strings are written, if you want to encode
861 before writing specifiy an `encoding`.
862
863 Example usage::
864
865 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
866 """
867 close = False
868 if isinstance(fp, basestring):
869 fp = file(fp, 'w')
870 close = True
871 try:
872 if encoding is not None:
873 iterable = (x.encode(encoding, errors) for x in self)
874 else:
875 iterable = self
876 if hasattr(fp, 'writelines'):
877 fp.writelines(iterable)
878 else:
879 for item in iterable:
880 fp.write(item)
881 finally:
882 if close:
883 fp.close()
884
Armin Ronacherc63243e2008-04-14 22:53:58 +0200885 def disable_buffering(self):
886 """Disable the output buffering."""
887 self._next = self._gen.next
888 self.buffered = False
889
890 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200891 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200892 if size <= 1:
893 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200894
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200895 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200896 buf = []
897 c_size = 0
898 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +0200899
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200900 while 1:
901 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200902 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200903 c = next()
904 push(c)
905 if c:
906 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200907 except StopIteration:
908 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200909 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200910 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200911 del buf[:]
912 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200913
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200914 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200915 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200916
917 def __iter__(self):
918 return self
919
920 def next(self):
921 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200922
923
924# hook in default template class. if anyone reads this comment: ignore that
925# it's possible to use custom templates ;-)
926Environment.template_class = Template