blob: 9145acb5e134ebcecd6bb0959ead94142221eaf8 [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 Ronacher12a316b2010-03-12 17:59:51 +010011import os
Armin Ronacherba3757b2008-04-16 19:43:16 +020012import sys
Armin Ronacherba6e25a2008-11-02 15:58:14 +010013from jinja2 import nodes
Armin Ronacher7259c762008-04-30 13:03:59 +020014from jinja2.defaults import *
Armin Ronacher9a0078d2008-08-13 18:24:17 +020015from jinja2.lexer import get_lexer, TokenStream
Armin Ronacher05530932008-04-20 13:27:49 +020016from jinja2.parser import Parser
Armin Ronacherbcb7c532008-04-11 16:30:34 +020017from jinja2.optimizer import optimize
18from jinja2.compiler import generate
Armin Ronacher74a0cd92009-02-19 15:56:53 +010019from jinja2.runtime import Undefined, new_context
Armin Ronacher31bbd9e2010-01-14 00:41:30 +010020from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \
21 TemplatesNotFound
Armin Ronacherba6e25a2008-11-02 15:58:14 +010022from jinja2.utils import import_string, LRUCache, Markup, missing, \
Armin Ronacher0d242be2010-02-10 01:35:13 +010023 concat, consume, internalcode, _encode_filename
Armin Ronacher07bc6842008-03-31 14:18:49 +020024
25
Armin Ronacher203bfcb2008-04-24 21:54:44 +020026# for direct template usage we have up to ten living environments
27_spontaneous_environments = LRUCache(10)
28
Armin Ronachera18872d2009-03-05 23:47:00 +010029# the function to create jinja traceback objects. This is dynamically
30# imported on the first exception in the exception handler.
31_make_traceback = None
32
Armin Ronacher203bfcb2008-04-24 21:54:44 +020033
Armin Ronacherb5124e62008-04-25 00:36:14 +020034def get_spontaneous_environment(*args):
Georg Brandl3e497b72008-09-19 09:55:17 +000035 """Return a new spontaneous environment. A spontaneous environment is an
36 unnamed and unaccessible (in theory) environment that is used for
37 templates generated from a string and not from the file system.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020038 """
39 try:
40 env = _spontaneous_environments.get(args)
41 except TypeError:
42 return Environment(*args)
43 if env is not None:
44 return env
45 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020046 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020047 return env
48
49
Armin Ronacher7259c762008-04-30 13:03:59 +020050def create_cache(size):
51 """Return the cache class for the given size."""
52 if size == 0:
53 return None
54 if size < 0:
55 return {}
56 return LRUCache(size)
57
58
Armin Ronacherccae0552008-10-05 23:08:58 +020059def copy_cache(cache):
60 """Create an empty copy of the given cache."""
61 if cache is None:
Armin Ronacher2bc1ef72008-12-08 15:21:26 +010062 return None
Armin Ronacherccae0552008-10-05 23:08:58 +020063 elif type(cache) is dict:
64 return {}
65 return LRUCache(cache.capacity)
66
67
Armin Ronacher7259c762008-04-30 13:03:59 +020068def load_extensions(environment, extensions):
69 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020070 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020071 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020072 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020073 for extension in extensions:
74 if isinstance(extension, basestring):
75 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020076 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020077 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020078
Armin Ronacher203bfcb2008-04-24 21:54:44 +020079
Armin Ronacher7259c762008-04-30 13:03:59 +020080def _environment_sanity_check(environment):
81 """Perform a sanity check on the environment."""
82 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
83 'be a subclass of undefined because filters depend on it.'
84 assert environment.block_start_string != \
85 environment.variable_start_string != \
86 environment.comment_start_string, 'block, variable and comment ' \
87 'start strings must be different'
Armin Ronacherf3c35c42008-05-23 23:18:14 +020088 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
89 'newline_sequence set to unknown line ending string.'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020090 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020091
92
Armin Ronacher07bc6842008-03-31 14:18:49 +020093class Environment(object):
Armin Ronacherf3c35c42008-05-23 23:18:14 +020094 r"""The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020095 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020096 globals and others. Instances of this class may be modified if
97 they are not shared and if no template was loaded so far.
98 Modifications on environments after the first template was loaded
99 will lead to surprising effects and undefined behavior.
100
101 Here the possible initialization parameters:
102
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200103 `block_start_string`
104 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200105
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200106 `block_end_string`
107 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200108
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200109 `variable_start_string`
110 The string marking the begin of a print statement.
111 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +0200112
Armin Ronacher63fd7982008-06-20 18:47:56 +0200113 `variable_end_string`
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200114 The string marking the end of a print statement. Defaults to
115 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200116
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200117 `comment_start_string`
118 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200119
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200120 `comment_end_string`
121 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200122
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200123 `line_statement_prefix`
124 If given and a string, this will be used as prefix for line based
125 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200126
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200127 `line_comment_prefix`
128 If given and a string, this will be used as prefix for line based
129 based comments. See also :ref:`line-statements`.
130
131 .. versionadded:: 2.2
132
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200133 `trim_blocks`
134 If this is set to ``True`` the first newline after a block is
135 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200136
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200137 `newline_sequence`
138 The sequence that starts a newline. Must be one of ``'\r'``,
139 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
140 useful default for Linux and OS X systems as well as web
141 applications.
142
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200143 `extensions`
144 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200145 as strings or extension classes. For more information have a
146 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200147
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200148 `optimized`
149 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200150
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200151 `undefined`
152 :class:`Undefined` or a subclass of it that is used to represent
153 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200154
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200155 `finalize`
Armin Ronacherd9ea26e2010-01-24 14:29:26 +0100156 A callable that can be used to process the result of a variable
157 expression before it is output. For example one can convert
158 `None` implicitly into an empty string here.
Armin Ronacherd1342312008-04-28 12:20:12 +0200159
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200160 `autoescape`
161 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200162 For more details about auto escaping see
163 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200164
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200165 `loader`
166 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200167
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200168 `cache_size`
169 The size of the cache. Per default this is ``50`` which means
170 that if more than 50 templates are loaded the loader will clean
171 out the least recently used template. If the cache size is set to
172 ``0`` templates are recompiled all the time, if the cache size is
173 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200174
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200175 `auto_reload`
176 Some loaders load templates from locations where the template
177 sources may change (ie: file system or database). If
178 `auto_reload` is set to `True` (default) every time a template is
179 requested the loader checks if the source changed and if yes, it
180 will reload the template. For higher performance it's possible to
181 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200182
183 `bytecode_cache`
184 If set to a bytecode cache object, this object will provide a
185 cache for the internal Jinja bytecode so that templates don't
186 have to be parsed if they were not changed.
Armin Ronachera816bf42008-09-17 21:28:01 +0200187
188 See :ref:`bytecode-cache` for more information.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200189 """
190
Armin Ronacherc63243e2008-04-14 22:53:58 +0200191 #: if this environment is sandboxed. Modifying this variable won't make
192 #: the environment sandboxed though. For a real sandboxed environment
193 #: have a look at jinja2.sandbox
194 sandboxed = False
195
Armin Ronacher7259c762008-04-30 13:03:59 +0200196 #: True if the environment is just an overlay
Armin Ronacher619eeed2009-07-09 21:55:29 +0200197 overlayed = False
Armin Ronacher7259c762008-04-30 13:03:59 +0200198
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200199 #: the environment this environment is linked to if it is an overlay
200 linked_to = None
201
Armin Ronacherc9705c22008-04-27 21:28:03 +0200202 #: shared environments have this set to `True`. A shared environment
203 #: must not be modified
204 shared = False
205
Armin Ronacher32ed6c92009-04-02 14:04:41 +0200206 #: these are currently EXPERIMENTAL undocumented features.
Armin Ronachera18872d2009-03-05 23:47:00 +0100207 exception_handler = None
208 exception_formatter = None
209
Armin Ronacher07bc6842008-03-31 14:18:49 +0200210 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200211 block_start_string=BLOCK_START_STRING,
212 block_end_string=BLOCK_END_STRING,
213 variable_start_string=VARIABLE_START_STRING,
214 variable_end_string=VARIABLE_END_STRING,
215 comment_start_string=COMMENT_START_STRING,
216 comment_end_string=COMMENT_END_STRING,
217 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200218 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200219 trim_blocks=TRIM_BLOCKS,
220 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200221 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200222 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200223 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200224 finalize=None,
225 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200226 loader=None,
227 cache_size=50,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200228 auto_reload=True,
229 bytecode_cache=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200230 # !!Important notice!!
231 # The constructor accepts quite a few arguments that should be
232 # passed by keyword rather than position. However it's important to
233 # not change the order of arguments because it's used at least
234 # internally in those cases:
235 # - spontaneus environments (i18n extension and Template)
236 # - unittests
237 # If parameter changes are required only add parameters at the end
238 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200239 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200240
241 # lexer / parser information
242 self.block_start_string = block_start_string
243 self.block_end_string = block_end_string
244 self.variable_start_string = variable_start_string
245 self.variable_end_string = variable_end_string
246 self.comment_start_string = comment_start_string
247 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200248 self.line_statement_prefix = line_statement_prefix
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200249 self.line_comment_prefix = line_comment_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200250 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200251 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200252
Armin Ronacherf59bac22008-04-20 13:11:43 +0200253 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200254 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200255 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200256 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200257 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200258
259 # defaults
260 self.filters = DEFAULT_FILTERS.copy()
261 self.tests = DEFAULT_TESTS.copy()
262 self.globals = DEFAULT_NAMESPACE.copy()
263
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200264 # set the loader provided
265 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200266 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200267 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200268 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200269 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200270
Armin Ronacherb5124e62008-04-25 00:36:14 +0200271 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200272 self.extensions = load_extensions(self, extensions)
273
274 _environment_sanity_check(self)
275
Armin Ronacher762079c2008-05-08 23:57:56 +0200276 def extend(self, **attributes):
277 """Add the items to the instance of the environment if they do not exist
278 yet. This is used by :ref:`extensions <writing-extensions>` to register
279 callbacks and configuration values without breaking inheritance.
280 """
281 for key, value in attributes.iteritems():
282 if not hasattr(self, key):
283 setattr(self, key, value)
284
Armin Ronacher7259c762008-04-30 13:03:59 +0200285 def overlay(self, block_start_string=missing, block_end_string=missing,
286 variable_start_string=missing, variable_end_string=missing,
287 comment_start_string=missing, comment_end_string=missing,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200288 line_statement_prefix=missing, line_comment_prefix=missing,
289 trim_blocks=missing, extensions=missing, optimized=missing,
290 undefined=missing, finalize=missing, autoescape=missing,
291 loader=missing, cache_size=missing, auto_reload=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200292 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200293 """Create a new overlay environment that shares all the data with the
Georg Brandl95632c42009-11-22 18:35:18 +0100294 current environment except of cache and the overridden attributes.
295 Extensions cannot be removed for an overlayed environment. An overlayed
Armin Ronacher7259c762008-04-30 13:03:59 +0200296 environment automatically gets all the extensions of the environment it
297 is linked to plus optional extra extensions.
298
299 Creating overlays should happen after the initial environment was set
300 up completely. Not all attributes are truly linked, some are just
301 copied over so modifications on the original environment may not shine
302 through.
303 """
304 args = dict(locals())
305 del args['self'], args['cache_size'], args['extensions']
306
307 rv = object.__new__(self.__class__)
308 rv.__dict__.update(self.__dict__)
Armin Ronacher619eeed2009-07-09 21:55:29 +0200309 rv.overlayed = True
Armin Ronacher7259c762008-04-30 13:03:59 +0200310 rv.linked_to = self
311
312 for key, value in args.iteritems():
313 if value is not missing:
314 setattr(rv, key, value)
315
316 if cache_size is not missing:
317 rv.cache = create_cache(cache_size)
Armin Ronacherccae0552008-10-05 23:08:58 +0200318 else:
319 rv.cache = copy_cache(self.cache)
Armin Ronacher7259c762008-04-30 13:03:59 +0200320
Armin Ronacher023b5e92008-05-08 11:03:10 +0200321 rv.extensions = {}
322 for key, value in self.extensions.iteritems():
323 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200324 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200325 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200326
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200327 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200328
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200329 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200330
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200331 def getitem(self, obj, argument):
332 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200333 try:
334 return obj[argument]
335 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200336 if isinstance(argument, basestring):
337 try:
338 attr = str(argument)
339 except:
340 pass
341 else:
342 try:
343 return getattr(obj, attr)
344 except AttributeError:
345 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200346 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200347
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200348 def getattr(self, obj, attribute):
349 """Get an item or attribute of an object but prefer the attribute.
350 Unlike :meth:`getitem` the attribute *must* be a bytestring.
351 """
352 try:
353 return getattr(obj, attribute)
354 except AttributeError:
355 pass
356 try:
357 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200358 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200359 return self.undefined(obj=obj, name=attribute)
360
Armin Ronacherd416a972009-02-24 22:58:00 +0100361 @internalcode
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200362 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200363 """Parse the sourcecode and return the abstract syntax tree. This
364 tree of nodes is used by the compiler to convert the template into
365 executable source- or bytecode. This is useful for debugging or to
366 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200367
368 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
369 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200370 """
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200371 try:
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700372 return self._parse(source, name, filename)
Armin Ronacher2a791922009-04-16 23:15:22 +0200373 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200374 exc_info = sys.exc_info()
375 self.handle_exception(exc_info, source_hint=source)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200376
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700377 def _parse(self, source, name, filename):
378 """Internal parsing function used by `parse` and `compile`."""
Armin Ronacher0d242be2010-02-10 01:35:13 +0100379 return Parser(self, source, name, _encode_filename(filename)).parse()
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700380
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 Ronacher64b08a02010-03-12 03:17:41 +0100419 def compile(self, source, name=None, filename=None, raw=False,
420 defer_init=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200421 """Compile a node or template source code. The `name` parameter is
422 the load name of the template after it was joined using
423 :meth:`join_path` if necessary, not the filename on the file system.
424 the `filename` parameter is the estimated filename of the template on
425 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200426 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200427
428 The return value of this method is a python code object. If the `raw`
429 parameter is `True` the return value will be a string with python
430 code equivalent to the bytecode returned otherwise. This method is
431 mainly used internally.
Armin Ronacher64b08a02010-03-12 03:17:41 +0100432
433 `defer_init` is use internally to aid the module code generator. This
434 causes the generated code to be able to import without the global
435 environment variable to be set.
436
437 .. versionadded:: 2.4
438 `defer_init` parameter added.
Armin Ronacher68f77672008-04-17 11:50:39 +0200439 """
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700440 source_hint = None
441 try:
442 if isinstance(source, basestring):
443 source_hint = source
444 source = self._parse(source, name, filename)
445 if self.optimized:
446 source = optimize(source, self)
Armin Ronacher64b08a02010-03-12 03:17:41 +0100447 source = generate(source, self, name, filename,
448 defer_init=defer_init)
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700449 if raw:
450 return source
451 if filename is None:
452 filename = '<template>'
Armin Ronacher0d242be2010-02-10 01:35:13 +0100453 else:
454 filename = _encode_filename(filename)
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700455 return compile(source, filename, 'exec')
456 except TemplateSyntaxError:
457 exc_info = sys.exc_info()
458 self.handle_exception(exc_info, source_hint=source)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200459
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100460 def compile_expression(self, source, undefined_to_none=True):
461 """A handy helper method that returns a callable that accepts keyword
462 arguments that appear as variables in the expression. If called it
463 returns the result of the expression.
464
465 This is useful if applications want to use the same rules as Jinja
466 in template "configuration files" or similar situations.
467
468 Example usage:
469
470 >>> env = Environment()
471 >>> expr = env.compile_expression('foo == 42')
472 >>> expr(foo=23)
473 False
474 >>> expr(foo=42)
475 True
476
477 Per default the return value is converted to `None` if the
478 expression returns an undefined value. This can be changed
479 by setting `undefined_to_none` to `False`.
480
481 >>> env.compile_expression('var')() is None
482 True
483 >>> env.compile_expression('var', undefined_to_none=False)()
484 Undefined
485
Armin Ronacher0319c662010-02-09 02:09:10 +0100486 .. versionadded:: 2.1
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100487 """
488 parser = Parser(self, source, state='variable')
Armin Ronacherbd357722009-08-05 20:25:06 +0200489 exc_info = None
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100490 try:
491 expr = parser.parse_expression()
492 if not parser.stream.eos:
493 raise TemplateSyntaxError('chunk after expression',
494 parser.stream.current.lineno,
495 None, None)
Armin Ronacher2a791922009-04-16 23:15:22 +0200496 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200497 exc_info = sys.exc_info()
498 if exc_info is not None:
499 self.handle_exception(exc_info, source_hint=source)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100500 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
501 template = self.from_string(nodes.Template(body, lineno=1))
502 return TemplateExpression(template, undefined_to_none)
503
Armin Ronacher64b08a02010-03-12 03:17:41 +0100504 def compile_templates(self, target, extensions=None, filter_func=None,
Armin Ronacher12a316b2010-03-12 17:59:51 +0100505 zip='deflated', log_function=None,
506 ignore_errors=True, py_compile=False):
Armin Ronacher64b08a02010-03-12 03:17:41 +0100507 """Compiles all the templates the loader can find, compiles them
Armin Ronacher12a316b2010-03-12 17:59:51 +0100508 and stores them in `target`. If `zip` is `None`, instead of in a
509 zipfile, the templates will be will be stored in a directory.
510 By default a deflate zip algorithm is used, to switch to
511 the stored algorithm, `zip` can be set to ``'stored'``.
Armin Ronacher64b08a02010-03-12 03:17:41 +0100512
513 `extensions` and `filter_func` are passed to :meth:`list_templates`.
514 Each template returned will be compiled to the target folder or
515 zipfile.
516
Armin Ronacher12a316b2010-03-12 17:59:51 +0100517 By default template compilation errors are ignored. In case a
518 log function is provided, errors are logged. If you want template
519 syntax errors to abort the compilation you can set `ignore_errors`
520 to `False` and you will get an exception on syntax errors.
521
522 If `py_compile` is set to `True` .pyc files will be written to the
523 target instead of standard .py files.
524
Armin Ronacher64b08a02010-03-12 03:17:41 +0100525 .. versionadded:: 2.4
526 """
527 from jinja2.loaders import ModuleLoader
Armin Ronacher12a316b2010-03-12 17:59:51 +0100528
Armin Ronacher64b08a02010-03-12 03:17:41 +0100529 if log_function is None:
530 log_function = lambda x: None
531
Armin Ronacher12a316b2010-03-12 17:59:51 +0100532 if py_compile:
533 import imp, struct, marshal
534 py_header = imp.get_magic() + '\xff\xff\xff\xff'
535
536 def write_file(filename, data):
537 if zip:
538 info = ZipInfo(filename)
539 info.external_attr = 0755 << 16L
540 zip_file.writestr(info, data)
541 else:
542 f = open(os.path.join(target, filename), 'wb')
543 try:
544 f.write(data)
545 finally:
546 f.close()
547
548 if zip is not None:
549 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
550 zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED,
551 stored=ZIP_STORED)[zip])
Armin Ronacher64b08a02010-03-12 03:17:41 +0100552 log_function('Compiling into Zip archive "%s"' % target)
553 else:
554 if not os.path.isdir(target):
555 os.makedirs(target)
556 log_function('Compiling into folder "%s"' % target)
557
558 try:
559 for name in self.list_templates(extensions, filter_func):
560 source, filename, _ = self.loader.get_source(self, name)
561 try:
562 code = self.compile(source, name, filename, True, True)
563 except TemplateSyntaxError, e:
Armin Ronacher12a316b2010-03-12 17:59:51 +0100564 if not ignore_errors:
565 raise
Armin Ronacher64b08a02010-03-12 03:17:41 +0100566 log_function('Could not compile "%s": %s' % (name, e))
567 continue
Armin Ronacher12a316b2010-03-12 17:59:51 +0100568
569 filename = ModuleLoader.get_module_filename(name)
570
571 if py_compile:
572 c = compile(code, _encode_filename(filename), 'exec')
573 write_file(filename + 'c', py_header + marshal.dumps(c))
574 log_function('Byte-compiled "%s" as %s' %
575 (name, filename + 'c'))
Armin Ronacher64b08a02010-03-12 03:17:41 +0100576 else:
Armin Ronacher12a316b2010-03-12 17:59:51 +0100577 write_file(filename, code)
578 log_function('Compiled "%s" as %s' % (name, filename))
Armin Ronacher64b08a02010-03-12 03:17:41 +0100579 finally:
580 if zip:
Armin Ronacher12a316b2010-03-12 17:59:51 +0100581 zip_file.close()
Armin Ronacher64b08a02010-03-12 03:17:41 +0100582
583 log_function('Finished compiling templates')
584
585 def list_templates(self, extensions=None, filter_func=None):
586 """Returns a list of templates for this environment. This requires
587 that the loader supports the loader's
588 :meth:`~BaseLoader.list_templates` method.
589
590 If there are other files in the template folder besides the
591 actual templates, the returned list can be filtered. There are two
592 ways: either `extensions` is set to a list of file extensions for
593 templates, or a `filter_func` can be provided which is a callable that
594 is passed a template name and should return `True` if it should end up
595 in the result list.
596
597 If the loader does not support that, a :exc:`TypeError` is raised.
598 """
599 x = self.loader.list_templates()
600 if extensions is not None:
601 if filter_func is not None:
602 raise TypeError('either extensions or filter_func '
603 'can be passed, but not both')
604 filter_func = lambda x: '.' in x and \
605 x.rsplit('.', 1)[1] in extensions
606 if filter_func is not None:
607 x = filter(filter_func, x)
608 return x
609
Armin Ronachera18872d2009-03-05 23:47:00 +0100610 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
611 """Exception handling helper. This is used internally to either raise
612 rewritten exceptions or return a rendered traceback for the template.
613 """
614 global _make_traceback
615 if exc_info is None:
616 exc_info = sys.exc_info()
Armin Ronacher32ed6c92009-04-02 14:04:41 +0200617
618 # the debugging module is imported when it's used for the first time.
619 # we're doing a lot of stuff there and for applications that do not
620 # get any exceptions in template rendering there is no need to load
621 # all of that.
Armin Ronachera18872d2009-03-05 23:47:00 +0100622 if _make_traceback is None:
623 from jinja2.debug import make_traceback as _make_traceback
624 traceback = _make_traceback(exc_info, source_hint)
625 if rendered and self.exception_formatter is not None:
626 return self.exception_formatter(traceback)
627 if self.exception_handler is not None:
628 self.exception_handler(traceback)
629 exc_type, exc_value, tb = traceback.standard_exc_info
630 raise exc_type, exc_value, tb
631
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200632 def join_path(self, template, parent):
633 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200634 relative to the loader root so this method returns the `template`
635 parameter unchanged, but if the paths should be relative to the
636 parent template, this function can be used to calculate the real
637 template name.
638
639 Subclasses may override this method and implement template path
640 joining here.
641 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200642 return template
643
Armin Ronacherd416a972009-02-24 22:58:00 +0100644 @internalcode
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100645 def _load_template(self, name, globals):
646 if self.loader is None:
647 raise TypeError('no loader for this environment specified')
648 if self.cache is not None:
649 template = self.cache.get(name)
650 if template is not None and (not self.auto_reload or \
651 template.is_up_to_date):
652 return template
653 template = self.loader.load(self, name, globals)
654 if self.cache is not None:
655 self.cache[name] = template
656 return template
657
658 @internalcode
Armin Ronacherfed44b52008-04-13 19:42:53 +0200659 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200660 """Load a template from the loader. If a loader is configured this
661 method ask the loader for the template and returns a :class:`Template`.
662 If the `parent` parameter is not `None`, :meth:`join_path` is called
663 to get the real template name before loading.
664
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200665 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200666 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200667
668 If the template does not exist a :exc:`TemplateNotFound` exception is
669 raised.
Armin Ronacherc2c63512010-02-16 17:37:17 +0100670
671 .. versionchanged:: 2.4
672 If `name` is a :class:`Template` object it is returned from the
673 function unchanged.
Armin Ronacherd1342312008-04-28 12:20:12 +0200674 """
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100675 if isinstance(name, Template):
676 return name
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200677 if parent is not None:
678 name = self.join_path(name, parent)
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100679 return self._load_template(name, self.make_globals(globals))
Armin Ronacher7259c762008-04-30 13:03:59 +0200680
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100681 @internalcode
682 def select_template(self, names, parent=None, globals=None):
683 """Works like :meth:`get_template` but tries a number of templates
684 before it fails. If it cannot find any of the templates, it will
685 raise a :exc:`TemplatesNotFound` exception.
Armin Ronacher7259c762008-04-30 13:03:59 +0200686
Armin Ronacher0319c662010-02-09 02:09:10 +0100687 .. versionadded:: 2.3
Armin Ronacherc2c63512010-02-16 17:37:17 +0100688
689 .. versionchanged:: 2.4
690 If `names` contains a :class:`Template` object it is returned
691 from the function unchanged.
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100692 """
693 if not names:
694 raise TemplatesNotFound(message=u'Tried to select from an empty list '
695 u'of templates.')
696 globals = self.make_globals(globals)
697 for name in names:
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100698 if isinstance(name, Template):
699 return name
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100700 if parent is not None:
701 name = self.join_path(name, parent)
702 try:
703 return self._load_template(name, globals)
704 except TemplateNotFound:
705 pass
706 raise TemplatesNotFound(names)
707
708 @internalcode
709 def get_or_select_template(self, template_name_or_list,
710 parent=None, globals=None):
Armin Ronacher04306792010-02-17 00:16:07 +0100711 """Does a typecheck and dispatches to :meth:`select_template`
712 if an iterable of template names is given, otherwise to
713 :meth:`get_template`.
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100714
Armin Ronacher0319c662010-02-09 02:09:10 +0100715 .. versionadded:: 2.3
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100716 """
717 if isinstance(template_name_or_list, basestring):
718 return self.get_template(template_name_or_list, parent, globals)
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100719 elif isinstance(template_name_or_list, Template):
720 return template_name_or_list
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100721 return self.select_template(template_name_or_list, parent, globals)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200722
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200723 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200724 """Load a template from a string. This parses the source given and
725 returns a :class:`Template` object.
726 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200727 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200728 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200729 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200730
731 def make_globals(self, d):
732 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200733 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200734 return self.globals
735 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200736
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200737
738class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200739 """The central template object. This class represents a compiled template
740 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200741
Armin Ronacherd1342312008-04-28 12:20:12 +0200742 Normally the template object is generated from an :class:`Environment` but
743 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200744 instance directly using the constructor. It takes the same arguments as
745 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200746
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200747 Every template object has a few methods and members that are guaranteed
748 to exist. However it's important that a template object should be
749 considered immutable. Modifications on the object are not supported.
750
751 Template objects created from the constructor rather than an environment
752 do have an `environment` attribute that points to a temporary environment
753 that is probably shared with other templates created with the constructor
754 and compatible settings.
755
756 >>> template = Template('Hello {{ name }}!')
757 >>> template.render(name='John Doe')
758 u'Hello John Doe!'
759
760 >>> stream = template.stream(name='John Doe')
761 >>> stream.next()
762 u'Hello John Doe!'
763 >>> stream.next()
764 Traceback (most recent call last):
765 ...
766 StopIteration
767 """
768
769 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200770 block_start_string=BLOCK_START_STRING,
771 block_end_string=BLOCK_END_STRING,
772 variable_start_string=VARIABLE_START_STRING,
773 variable_end_string=VARIABLE_END_STRING,
774 comment_start_string=COMMENT_START_STRING,
775 comment_end_string=COMMENT_END_STRING,
776 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200777 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200778 trim_blocks=TRIM_BLOCKS,
779 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200780 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200781 optimized=True,
782 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200783 finalize=None,
784 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200785 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200786 block_start_string, block_end_string, variable_start_string,
787 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200788 line_statement_prefix, line_comment_prefix, trim_blocks,
789 newline_sequence, frozenset(extensions), optimized, undefined,
790 finalize, autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200791 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200792
Armin Ronacher7259c762008-04-30 13:03:59 +0200793 @classmethod
794 def from_code(cls, environment, code, globals, uptodate=None):
795 """Creates a template object from compiled code and the globals. This
796 is used by the loaders and environment to create a template object.
797 """
Armin Ronacher7259c762008-04-30 13:03:59 +0200798 namespace = {
Armin Ronacher64b08a02010-03-12 03:17:41 +0100799 'environment': environment,
800 '__file__': code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200801 }
802 exec code in namespace
Armin Ronacher64b08a02010-03-12 03:17:41 +0100803 rv = cls._from_namespace(environment, namespace, globals)
804 rv._uptodate = uptodate
805 return rv
806
807 @classmethod
808 def from_module_dict(cls, environment, module_dict, globals):
809 """Creates a template object from a module. This is used by the
810 module loader to create a template object.
811
812 .. versionadded:: 2.4
813 """
814 return cls._from_namespace(environment, module_dict, globals)
815
816 @classmethod
817 def _from_namespace(cls, environment, namespace, globals):
818 t = object.__new__(cls)
Armin Ronacher7259c762008-04-30 13:03:59 +0200819 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200820 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200821 t.name = namespace['name']
Armin Ronacher64b08a02010-03-12 03:17:41 +0100822 t.filename = namespace['__file__']
Armin Ronacher7259c762008-04-30 13:03:59 +0200823 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200824
Georg Brandl3e497b72008-09-19 09:55:17 +0000825 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200826 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200827 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200828
829 # debug and loader helpers
830 t._debug_info = namespace['debug_info']
Armin Ronacher64b08a02010-03-12 03:17:41 +0100831 t._uptodate = None
832
833 # store the reference
834 namespace['environment'] = environment
835 namespace['__jinja_template__'] = t
Armin Ronacher7259c762008-04-30 13:03:59 +0200836
837 return t
838
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200839 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200840 """This method accepts the same arguments as the `dict` constructor:
841 A dict, a dict subclass or some keyword arguments. If no arguments
842 are given the context will be empty. These two calls do the same::
843
844 template.render(knights='that say nih')
845 template.render({'knights': 'that say nih'})
846
847 This will return the rendered template as unicode string.
848 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200849 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200850 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200851 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200852 except:
Armin Ronacherbd357722009-08-05 20:25:06 +0200853 exc_info = sys.exc_info()
854 return self.environment.handle_exception(exc_info, True)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200855
856 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200857 """Works exactly like :meth:`generate` but returns a
858 :class:`TemplateStream`.
859 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200860 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200861
862 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200863 """For very large templates it can be useful to not render the whole
864 template at once but evaluate each statement after another and yield
865 piece for piece. This method basically does exactly that and returns
866 a generator that yields one item after another as unicode strings.
867
868 It accepts the same arguments as :meth:`render`.
869 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200870 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200871 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200872 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200873 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200874 except:
Armin Ronacherbd357722009-08-05 20:25:06 +0200875 exc_info = sys.exc_info()
876 else:
877 return
878 yield self.environment.handle_exception(exc_info, True)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200879
Armin Ronacher673aa882008-10-04 18:06:57 +0200880 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200881 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200882 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200883 are added to the context. If shared is set to `True` the data
884 is passed as it to the context without adding the globals.
885
886 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200887 """
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100888 return new_context(self.environment, self.name, self.blocks,
889 vars, shared, self.globals, locals)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200890
Armin Ronacher673aa882008-10-04 18:06:57 +0200891 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200892 """This method works like the :attr:`module` attribute when called
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100893 without arguments but it will evaluate the template on every call
894 rather than caching it. It's also possible to provide
Armin Ronacher7ceced52008-05-03 10:15:31 +0200895 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200896 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200897 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200898 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200899
Armin Ronacherd84ec462008-04-29 13:43:16 +0200900 @property
901 def module(self):
902 """The template as module. This is used for imports in the
903 template runtime but is also useful if one wants to access
904 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200905
Armin Ronacherd84ec462008-04-29 13:43:16 +0200906 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
907 >>> unicode(t.module)
908 u'23'
909 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200910 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200911 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200912 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200913 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200914 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200915 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200916
Armin Ronacherba3757b2008-04-16 19:43:16 +0200917 def get_corresponding_lineno(self, lineno):
918 """Return the source line number of a line number in the
919 generated bytecode as they are not in sync.
920 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200921 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200922 if code_line <= lineno:
923 return template_line
924 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200925
Armin Ronacher9a822052008-04-17 18:44:07 +0200926 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200927 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200928 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200929 if self._uptodate is None:
930 return True
931 return self._uptodate()
932
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200933 @property
934 def debug_info(self):
935 """The debug info mapping."""
936 return [tuple(map(int, x.split('='))) for x in
937 self._debug_info.split('&')]
938
Armin Ronacherc63243e2008-04-14 22:53:58 +0200939 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200940 if self.name is None:
941 name = 'memory:%x' % id(self)
942 else:
943 name = repr(self.name)
944 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200945
946
Armin Ronacherd84ec462008-04-29 13:43:16 +0200947class TemplateModule(object):
948 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200949 template are available as attributes on this object. Additionally
950 converting it into an unicode- or bytestrings renders the contents.
951 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200952
953 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200954 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200955 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200956 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200957
Armin Ronacher0faa8612010-02-09 15:04:51 +0100958 def __html__(self):
959 return Markup(concat(self._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200960
961 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200962 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200963
Armin Ronacheracbd4082010-02-10 00:07:43 +0100964 # unicode goes after __str__ because we configured 2to3 to rename
965 # __unicode__ to __str__. because the 2to3 tree is not designed to
966 # remove nodes from it, we leave the above __str__ around and let
967 # it override at runtime.
Armin Ronacher790b8a82010-02-10 00:05:46 +0100968 def __unicode__(self):
969 return concat(self._body_stream)
970
Armin Ronacher963f97d2008-04-25 11:44:59 +0200971 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200972 if self.__name__ is None:
973 name = 'memory:%x' % id(self)
974 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200975 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200976 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200977
978
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100979class TemplateExpression(object):
980 """The :meth:`jinja2.Environment.compile_expression` method returns an
981 instance of this object. It encapsulates the expression-like access
982 to the template with an expression it wraps.
983 """
984
985 def __init__(self, template, undefined_to_none):
986 self._template = template
987 self._undefined_to_none = undefined_to_none
988
989 def __call__(self, *args, **kwargs):
990 context = self._template.new_context(dict(*args, **kwargs))
991 consume(self._template.root_render_func(context))
992 rv = context.vars['result']
993 if self._undefined_to_none and isinstance(rv, Undefined):
994 rv = None
995 return rv
996
997
Armin Ronacherc63243e2008-04-14 22:53:58 +0200998class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200999 """A template stream works pretty much like an ordinary python generator
1000 but it can buffer multiple items to reduce the number of total iterations.
1001 Per default the output is unbuffered which means that for every unbuffered
1002 instruction in the template one unicode string is yielded.
1003
1004 If buffering is enabled with a buffer size of 5, five items are combined
1005 into a new unicode string. This is mainly useful if you are streaming
1006 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001007 """
Armin Ronacherc63243e2008-04-14 22:53:58 +02001008
1009 def __init__(self, gen):
1010 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +02001011 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +02001012
Armin Ronacher74b51062008-06-17 11:28:59 +02001013 def dump(self, fp, encoding=None, errors='strict'):
1014 """Dump the complete stream into a file or file-like object.
1015 Per default unicode strings are written, if you want to encode
1016 before writing specifiy an `encoding`.
1017
1018 Example usage::
1019
1020 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
1021 """
1022 close = False
1023 if isinstance(fp, basestring):
1024 fp = file(fp, 'w')
1025 close = True
1026 try:
1027 if encoding is not None:
1028 iterable = (x.encode(encoding, errors) for x in self)
1029 else:
1030 iterable = self
1031 if hasattr(fp, 'writelines'):
1032 fp.writelines(iterable)
1033 else:
1034 for item in iterable:
1035 fp.write(item)
1036 finally:
1037 if close:
1038 fp.close()
1039
Armin Ronacherc63243e2008-04-14 22:53:58 +02001040 def disable_buffering(self):
1041 """Disable the output buffering."""
1042 self._next = self._gen.next
1043 self.buffered = False
1044
1045 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +02001046 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +02001047 if size <= 1:
1048 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +02001049
Armin Ronacher5dfbfc12008-05-25 18:10:12 +02001050 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +02001051 buf = []
1052 c_size = 0
1053 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +02001054
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001055 while 1:
1056 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +02001057 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +02001058 c = next()
1059 push(c)
1060 if c:
1061 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001062 except StopIteration:
1063 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +02001064 return
Armin Ronacherde6bf712008-04-26 01:44:14 +02001065 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001066 del buf[:]
1067 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +02001068
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001069 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +02001070 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +02001071
1072 def __iter__(self):
1073 return self
1074
1075 def next(self):
1076 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001077
1078
1079# hook in default template class. if anyone reads this comment: ignore that
1080# it's possible to use custom templates ;-)
1081Environment.template_class = Template