blob: 742bc1c496493d18754571b1042695e15fdc2f8e [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 Ronacher0d242be2010-02-10 01:35:13 +010022 concat, consume, internalcode, _encode_filename
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`
Armin Ronacherd9ea26e2010-01-24 14:29:26 +0100155 A callable that can be used to process the result of a variable
156 expression before it is output. For example one can convert
157 `None` implicitly into an empty string here.
Armin Ronacherd1342312008-04-28 12:20:12 +0200158
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200159 `autoescape`
160 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200161 For more details about auto escaping see
162 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200163
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200164 `loader`
165 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200166
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200167 `cache_size`
168 The size of the cache. Per default this is ``50`` which means
169 that if more than 50 templates are loaded the loader will clean
170 out the least recently used template. If the cache size is set to
171 ``0`` templates are recompiled all the time, if the cache size is
172 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200173
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200174 `auto_reload`
175 Some loaders load templates from locations where the template
176 sources may change (ie: file system or database). If
177 `auto_reload` is set to `True` (default) every time a template is
178 requested the loader checks if the source changed and if yes, it
179 will reload the template. For higher performance it's possible to
180 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200181
182 `bytecode_cache`
183 If set to a bytecode cache object, this object will provide a
184 cache for the internal Jinja bytecode so that templates don't
185 have to be parsed if they were not changed.
Armin Ronachera816bf42008-09-17 21:28:01 +0200186
187 See :ref:`bytecode-cache` for more information.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200188 """
189
Armin Ronacherc63243e2008-04-14 22:53:58 +0200190 #: if this environment is sandboxed. Modifying this variable won't make
191 #: the environment sandboxed though. For a real sandboxed environment
192 #: have a look at jinja2.sandbox
193 sandboxed = False
194
Armin Ronacher7259c762008-04-30 13:03:59 +0200195 #: True if the environment is just an overlay
Armin Ronacher619eeed2009-07-09 21:55:29 +0200196 overlayed = False
Armin Ronacher7259c762008-04-30 13:03:59 +0200197
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200198 #: the environment this environment is linked to if it is an overlay
199 linked_to = None
200
Armin Ronacherc9705c22008-04-27 21:28:03 +0200201 #: shared environments have this set to `True`. A shared environment
202 #: must not be modified
203 shared = False
204
Armin Ronacher32ed6c92009-04-02 14:04:41 +0200205 #: these are currently EXPERIMENTAL undocumented features.
Armin Ronachera18872d2009-03-05 23:47:00 +0100206 exception_handler = None
207 exception_formatter = None
208
Armin Ronacher07bc6842008-03-31 14:18:49 +0200209 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200210 block_start_string=BLOCK_START_STRING,
211 block_end_string=BLOCK_END_STRING,
212 variable_start_string=VARIABLE_START_STRING,
213 variable_end_string=VARIABLE_END_STRING,
214 comment_start_string=COMMENT_START_STRING,
215 comment_end_string=COMMENT_END_STRING,
216 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200217 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200218 trim_blocks=TRIM_BLOCKS,
219 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200220 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200221 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200222 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200223 finalize=None,
224 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200225 loader=None,
226 cache_size=50,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200227 auto_reload=True,
228 bytecode_cache=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200229 # !!Important notice!!
230 # The constructor accepts quite a few arguments that should be
231 # passed by keyword rather than position. However it's important to
232 # not change the order of arguments because it's used at least
233 # internally in those cases:
234 # - spontaneus environments (i18n extension and Template)
235 # - unittests
236 # If parameter changes are required only add parameters at the end
237 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200238 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200239
240 # lexer / parser information
241 self.block_start_string = block_start_string
242 self.block_end_string = block_end_string
243 self.variable_start_string = variable_start_string
244 self.variable_end_string = variable_end_string
245 self.comment_start_string = comment_start_string
246 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200247 self.line_statement_prefix = line_statement_prefix
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200248 self.line_comment_prefix = line_comment_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200249 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200250 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200251
Armin Ronacherf59bac22008-04-20 13:11:43 +0200252 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200253 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200254 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200255 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200256 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200257
258 # defaults
259 self.filters = DEFAULT_FILTERS.copy()
260 self.tests = DEFAULT_TESTS.copy()
261 self.globals = DEFAULT_NAMESPACE.copy()
262
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200263 # set the loader provided
264 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200265 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200266 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200267 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200268 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200269
Armin Ronacherb5124e62008-04-25 00:36:14 +0200270 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200271 self.extensions = load_extensions(self, extensions)
272
273 _environment_sanity_check(self)
274
Armin Ronacher762079c2008-05-08 23:57:56 +0200275 def extend(self, **attributes):
276 """Add the items to the instance of the environment if they do not exist
277 yet. This is used by :ref:`extensions <writing-extensions>` to register
278 callbacks and configuration values without breaking inheritance.
279 """
280 for key, value in attributes.iteritems():
281 if not hasattr(self, key):
282 setattr(self, key, value)
283
Armin Ronacher7259c762008-04-30 13:03:59 +0200284 def overlay(self, block_start_string=missing, block_end_string=missing,
285 variable_start_string=missing, variable_end_string=missing,
286 comment_start_string=missing, comment_end_string=missing,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200287 line_statement_prefix=missing, line_comment_prefix=missing,
288 trim_blocks=missing, extensions=missing, optimized=missing,
289 undefined=missing, finalize=missing, autoescape=missing,
290 loader=missing, cache_size=missing, auto_reload=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200291 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200292 """Create a new overlay environment that shares all the data with the
Georg Brandl95632c42009-11-22 18:35:18 +0100293 current environment except of cache and the overridden attributes.
294 Extensions cannot be removed for an overlayed environment. An overlayed
Armin Ronacher7259c762008-04-30 13:03:59 +0200295 environment automatically gets all the extensions of the environment it
296 is linked to plus optional extra extensions.
297
298 Creating overlays should happen after the initial environment was set
299 up completely. Not all attributes are truly linked, some are just
300 copied over so modifications on the original environment may not shine
301 through.
302 """
303 args = dict(locals())
304 del args['self'], args['cache_size'], args['extensions']
305
306 rv = object.__new__(self.__class__)
307 rv.__dict__.update(self.__dict__)
Armin Ronacher619eeed2009-07-09 21:55:29 +0200308 rv.overlayed = True
Armin Ronacher7259c762008-04-30 13:03:59 +0200309 rv.linked_to = self
310
311 for key, value in args.iteritems():
312 if value is not missing:
313 setattr(rv, key, value)
314
315 if cache_size is not missing:
316 rv.cache = create_cache(cache_size)
Armin Ronacherccae0552008-10-05 23:08:58 +0200317 else:
318 rv.cache = copy_cache(self.cache)
Armin Ronacher7259c762008-04-30 13:03:59 +0200319
Armin Ronacher023b5e92008-05-08 11:03:10 +0200320 rv.extensions = {}
321 for key, value in self.extensions.iteritems():
322 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200323 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200324 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200325
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200326 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200327
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200328 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200329
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200330 def getitem(self, obj, argument):
331 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200332 try:
333 return obj[argument]
334 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200335 if isinstance(argument, basestring):
336 try:
337 attr = str(argument)
338 except:
339 pass
340 else:
341 try:
342 return getattr(obj, attr)
343 except AttributeError:
344 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200345 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200346
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200347 def getattr(self, obj, attribute):
348 """Get an item or attribute of an object but prefer the attribute.
349 Unlike :meth:`getitem` the attribute *must* be a bytestring.
350 """
351 try:
352 return getattr(obj, attribute)
353 except AttributeError:
354 pass
355 try:
356 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200357 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200358 return self.undefined(obj=obj, name=attribute)
359
Armin Ronacherd416a972009-02-24 22:58:00 +0100360 @internalcode
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200361 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200362 """Parse the sourcecode and return the abstract syntax tree. This
363 tree of nodes is used by the compiler to convert the template into
364 executable source- or bytecode. This is useful for debugging or to
365 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200366
367 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
368 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200369 """
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200370 try:
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700371 return self._parse(source, name, filename)
Armin Ronacher2a791922009-04-16 23:15:22 +0200372 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200373 exc_info = sys.exc_info()
374 self.handle_exception(exc_info, source_hint=source)
Armin Ronacher07bc6842008-03-31 14:18:49 +0200375
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700376 def _parse(self, source, name, filename):
377 """Internal parsing function used by `parse` and `compile`."""
Armin Ronacher0d242be2010-02-10 01:35:13 +0100378 return Parser(self, source, name, _encode_filename(filename)).parse()
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700379
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200380 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200381 """Lex the given sourcecode and return a generator that yields
382 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200383 This can be useful for :ref:`extension development <writing-extensions>`
384 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200385
386 This does not perform preprocessing. If you want the preprocessing
387 of the extensions to be applied you have to filter source through
388 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200389 """
Armin Ronacherccae0552008-10-05 23:08:58 +0200390 source = unicode(source)
391 try:
392 return self.lexer.tokeniter(source, name, filename)
Armin Ronacher2a791922009-04-16 23:15:22 +0200393 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200394 exc_info = sys.exc_info()
395 self.handle_exception(exc_info, source_hint=source)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200396
397 def preprocess(self, source, name=None, filename=None):
398 """Preprocesses the source with all extensions. This is automatically
399 called for all parsing and compiling methods but *not* for :meth:`lex`
400 because there you usually only want the actual source tokenized.
401 """
402 return reduce(lambda s, e: e.preprocess(s, name, filename),
403 self.extensions.itervalues(), unicode(source))
404
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100405 def _tokenize(self, source, name, filename=None, state=None):
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200406 """Called by the parser to do the preprocessing and filtering
407 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
408 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200409 source = self.preprocess(source, name, filename)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100410 stream = self.lexer.tokenize(source, name, filename, state)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200411 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200412 stream = ext.filter_stream(stream)
413 if not isinstance(stream, TokenStream):
414 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200415 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200416
Armin Ronacherd416a972009-02-24 22:58:00 +0100417 @internalcode
Armin Ronacher64b08a02010-03-12 03:17:41 +0100418 def compile(self, source, name=None, filename=None, raw=False,
419 defer_init=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 Ronacher64b08a02010-03-12 03:17:41 +0100431
432 `defer_init` is use internally to aid the module code generator. This
433 causes the generated code to be able to import without the global
434 environment variable to be set.
435
436 .. versionadded:: 2.4
437 `defer_init` parameter added.
Armin Ronacher68f77672008-04-17 11:50:39 +0200438 """
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700439 source_hint = None
440 try:
441 if isinstance(source, basestring):
442 source_hint = source
443 source = self._parse(source, name, filename)
444 if self.optimized:
445 source = optimize(source, self)
Armin Ronacher64b08a02010-03-12 03:17:41 +0100446 source = generate(source, self, name, filename,
447 defer_init=defer_init)
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700448 if raw:
449 return source
450 if filename is None:
451 filename = '<template>'
Armin Ronacher0d242be2010-02-10 01:35:13 +0100452 else:
453 filename = _encode_filename(filename)
Armin Ronacherefcc0e52009-09-13 00:22:50 -0700454 return compile(source, filename, 'exec')
455 except TemplateSyntaxError:
456 exc_info = sys.exc_info()
457 self.handle_exception(exc_info, source_hint=source)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200458
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100459 def compile_expression(self, source, undefined_to_none=True):
460 """A handy helper method that returns a callable that accepts keyword
461 arguments that appear as variables in the expression. If called it
462 returns the result of the expression.
463
464 This is useful if applications want to use the same rules as Jinja
465 in template "configuration files" or similar situations.
466
467 Example usage:
468
469 >>> env = Environment()
470 >>> expr = env.compile_expression('foo == 42')
471 >>> expr(foo=23)
472 False
473 >>> expr(foo=42)
474 True
475
476 Per default the return value is converted to `None` if the
477 expression returns an undefined value. This can be changed
478 by setting `undefined_to_none` to `False`.
479
480 >>> env.compile_expression('var')() is None
481 True
482 >>> env.compile_expression('var', undefined_to_none=False)()
483 Undefined
484
Armin Ronacher0319c662010-02-09 02:09:10 +0100485 .. versionadded:: 2.1
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100486 """
487 parser = Parser(self, source, state='variable')
Armin Ronacherbd357722009-08-05 20:25:06 +0200488 exc_info = None
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100489 try:
490 expr = parser.parse_expression()
491 if not parser.stream.eos:
492 raise TemplateSyntaxError('chunk after expression',
493 parser.stream.current.lineno,
494 None, None)
Armin Ronacher2a791922009-04-16 23:15:22 +0200495 except TemplateSyntaxError:
Armin Ronacherbd357722009-08-05 20:25:06 +0200496 exc_info = sys.exc_info()
497 if exc_info is not None:
498 self.handle_exception(exc_info, source_hint=source)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100499 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
500 template = self.from_string(nodes.Template(body, lineno=1))
501 return TemplateExpression(template, undefined_to_none)
502
Armin Ronacher64b08a02010-03-12 03:17:41 +0100503 def compile_templates(self, target, extensions=None, filter_func=None,
504 zip=True, log_function=None):
505 """Compiles all the templates the loader can find, compiles them
506 and stores them in `target`. If `zip` is true, a zipfile will be
507 written, otherwise the templates are stored in a directory.
508
509 `extensions` and `filter_func` are passed to :meth:`list_templates`.
510 Each template returned will be compiled to the target folder or
511 zipfile.
512
513 .. versionadded:: 2.4
514 """
515 from jinja2.loaders import ModuleLoader
516 if log_function is None:
517 log_function = lambda x: None
518
519 if zip:
520 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED
521 f = ZipFile(target, 'w', ZIP_DEFLATED)
522 log_function('Compiling into Zip archive "%s"' % target)
523 else:
524 if not os.path.isdir(target):
525 os.makedirs(target)
526 log_function('Compiling into folder "%s"' % target)
527
528 try:
529 for name in self.list_templates(extensions, filter_func):
530 source, filename, _ = self.loader.get_source(self, name)
531 try:
532 code = self.compile(source, name, filename, True, True)
533 except TemplateSyntaxError, e:
534 log_function('Could not compile "%s": %s' % (name, e))
535 continue
536 module = ModuleLoader.get_module_filename(name)
537 if zip:
538 info = ZipInfo(module)
539 info.external_attr = 0755 << 16L
540 f.writestr(info, code)
541 else:
542 f = open(filename, 'w')
543 try:
544 f.write(code)
545 finally:
546 f.close()
547 log_function('Compiled "%s" as %s' % (name, module))
548 finally:
549 if zip:
550 f.close()
551
552 log_function('Finished compiling templates')
553
554 def list_templates(self, extensions=None, filter_func=None):
555 """Returns a list of templates for this environment. This requires
556 that the loader supports the loader's
557 :meth:`~BaseLoader.list_templates` method.
558
559 If there are other files in the template folder besides the
560 actual templates, the returned list can be filtered. There are two
561 ways: either `extensions` is set to a list of file extensions for
562 templates, or a `filter_func` can be provided which is a callable that
563 is passed a template name and should return `True` if it should end up
564 in the result list.
565
566 If the loader does not support that, a :exc:`TypeError` is raised.
567 """
568 x = self.loader.list_templates()
569 if extensions is not None:
570 if filter_func is not None:
571 raise TypeError('either extensions or filter_func '
572 'can be passed, but not both')
573 filter_func = lambda x: '.' in x and \
574 x.rsplit('.', 1)[1] in extensions
575 if filter_func is not None:
576 x = filter(filter_func, x)
577 return x
578
Armin Ronachera18872d2009-03-05 23:47:00 +0100579 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
580 """Exception handling helper. This is used internally to either raise
581 rewritten exceptions or return a rendered traceback for the template.
582 """
583 global _make_traceback
584 if exc_info is None:
585 exc_info = sys.exc_info()
Armin Ronacher32ed6c92009-04-02 14:04:41 +0200586
587 # the debugging module is imported when it's used for the first time.
588 # we're doing a lot of stuff there and for applications that do not
589 # get any exceptions in template rendering there is no need to load
590 # all of that.
Armin Ronachera18872d2009-03-05 23:47:00 +0100591 if _make_traceback is None:
592 from jinja2.debug import make_traceback as _make_traceback
593 traceback = _make_traceback(exc_info, source_hint)
594 if rendered and self.exception_formatter is not None:
595 return self.exception_formatter(traceback)
596 if self.exception_handler is not None:
597 self.exception_handler(traceback)
598 exc_type, exc_value, tb = traceback.standard_exc_info
599 raise exc_type, exc_value, tb
600
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200601 def join_path(self, template, parent):
602 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200603 relative to the loader root so this method returns the `template`
604 parameter unchanged, but if the paths should be relative to the
605 parent template, this function can be used to calculate the real
606 template name.
607
608 Subclasses may override this method and implement template path
609 joining here.
610 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200611 return template
612
Armin Ronacherd416a972009-02-24 22:58:00 +0100613 @internalcode
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100614 def _load_template(self, name, globals):
615 if self.loader is None:
616 raise TypeError('no loader for this environment specified')
617 if self.cache is not None:
618 template = self.cache.get(name)
619 if template is not None and (not self.auto_reload or \
620 template.is_up_to_date):
621 return template
622 template = self.loader.load(self, name, globals)
623 if self.cache is not None:
624 self.cache[name] = template
625 return template
626
627 @internalcode
Armin Ronacherfed44b52008-04-13 19:42:53 +0200628 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200629 """Load a template from the loader. If a loader is configured this
630 method ask the loader for the template and returns a :class:`Template`.
631 If the `parent` parameter is not `None`, :meth:`join_path` is called
632 to get the real template name before loading.
633
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200634 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200635 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200636
637 If the template does not exist a :exc:`TemplateNotFound` exception is
638 raised.
Armin Ronacherc2c63512010-02-16 17:37:17 +0100639
640 .. versionchanged:: 2.4
641 If `name` is a :class:`Template` object it is returned from the
642 function unchanged.
Armin Ronacherd1342312008-04-28 12:20:12 +0200643 """
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100644 if isinstance(name, Template):
645 return name
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200646 if parent is not None:
647 name = self.join_path(name, parent)
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100648 return self._load_template(name, self.make_globals(globals))
Armin Ronacher7259c762008-04-30 13:03:59 +0200649
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100650 @internalcode
651 def select_template(self, names, parent=None, globals=None):
652 """Works like :meth:`get_template` but tries a number of templates
653 before it fails. If it cannot find any of the templates, it will
654 raise a :exc:`TemplatesNotFound` exception.
Armin Ronacher7259c762008-04-30 13:03:59 +0200655
Armin Ronacher0319c662010-02-09 02:09:10 +0100656 .. versionadded:: 2.3
Armin Ronacherc2c63512010-02-16 17:37:17 +0100657
658 .. versionchanged:: 2.4
659 If `names` contains a :class:`Template` object it is returned
660 from the function unchanged.
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100661 """
662 if not names:
663 raise TemplatesNotFound(message=u'Tried to select from an empty list '
664 u'of templates.')
665 globals = self.make_globals(globals)
666 for name in names:
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100667 if isinstance(name, Template):
668 return name
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100669 if parent is not None:
670 name = self.join_path(name, parent)
671 try:
672 return self._load_template(name, globals)
673 except TemplateNotFound:
674 pass
675 raise TemplatesNotFound(names)
676
677 @internalcode
678 def get_or_select_template(self, template_name_or_list,
679 parent=None, globals=None):
Armin Ronacher04306792010-02-17 00:16:07 +0100680 """Does a typecheck and dispatches to :meth:`select_template`
681 if an iterable of template names is given, otherwise to
682 :meth:`get_template`.
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100683
Armin Ronacher0319c662010-02-09 02:09:10 +0100684 .. versionadded:: 2.3
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100685 """
686 if isinstance(template_name_or_list, basestring):
687 return self.get_template(template_name_or_list, parent, globals)
Armin Ronacher9165d3e2010-02-16 17:35:59 +0100688 elif isinstance(template_name_or_list, Template):
689 return template_name_or_list
Armin Ronacher31bbd9e2010-01-14 00:41:30 +0100690 return self.select_template(template_name_or_list, parent, globals)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200691
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200692 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200693 """Load a template from a string. This parses the source given and
694 returns a :class:`Template` object.
695 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200696 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200697 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200698 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200699
700 def make_globals(self, d):
701 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200702 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200703 return self.globals
704 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200705
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200706
707class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200708 """The central template object. This class represents a compiled template
709 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200710
Armin Ronacherd1342312008-04-28 12:20:12 +0200711 Normally the template object is generated from an :class:`Environment` but
712 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200713 instance directly using the constructor. It takes the same arguments as
714 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200715
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200716 Every template object has a few methods and members that are guaranteed
717 to exist. However it's important that a template object should be
718 considered immutable. Modifications on the object are not supported.
719
720 Template objects created from the constructor rather than an environment
721 do have an `environment` attribute that points to a temporary environment
722 that is probably shared with other templates created with the constructor
723 and compatible settings.
724
725 >>> template = Template('Hello {{ name }}!')
726 >>> template.render(name='John Doe')
727 u'Hello John Doe!'
728
729 >>> stream = template.stream(name='John Doe')
730 >>> stream.next()
731 u'Hello John Doe!'
732 >>> stream.next()
733 Traceback (most recent call last):
734 ...
735 StopIteration
736 """
737
738 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200739 block_start_string=BLOCK_START_STRING,
740 block_end_string=BLOCK_END_STRING,
741 variable_start_string=VARIABLE_START_STRING,
742 variable_end_string=VARIABLE_END_STRING,
743 comment_start_string=COMMENT_START_STRING,
744 comment_end_string=COMMENT_END_STRING,
745 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200746 line_comment_prefix=LINE_COMMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200747 trim_blocks=TRIM_BLOCKS,
748 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200749 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200750 optimized=True,
751 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200752 finalize=None,
753 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200754 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200755 block_start_string, block_end_string, variable_start_string,
756 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacher59b6bd52009-03-30 21:00:16 +0200757 line_statement_prefix, line_comment_prefix, trim_blocks,
758 newline_sequence, frozenset(extensions), optimized, undefined,
759 finalize, autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200760 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200761
Armin Ronacher7259c762008-04-30 13:03:59 +0200762 @classmethod
763 def from_code(cls, environment, code, globals, uptodate=None):
764 """Creates a template object from compiled code and the globals. This
765 is used by the loaders and environment to create a template object.
766 """
Armin Ronacher7259c762008-04-30 13:03:59 +0200767 namespace = {
Armin Ronacher64b08a02010-03-12 03:17:41 +0100768 'environment': environment,
769 '__file__': code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200770 }
771 exec code in namespace
Armin Ronacher64b08a02010-03-12 03:17:41 +0100772 rv = cls._from_namespace(environment, namespace, globals)
773 rv._uptodate = uptodate
774 return rv
775
776 @classmethod
777 def from_module_dict(cls, environment, module_dict, globals):
778 """Creates a template object from a module. This is used by the
779 module loader to create a template object.
780
781 .. versionadded:: 2.4
782 """
783 return cls._from_namespace(environment, module_dict, globals)
784
785 @classmethod
786 def _from_namespace(cls, environment, namespace, globals):
787 t = object.__new__(cls)
Armin Ronacher7259c762008-04-30 13:03:59 +0200788 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200789 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200790 t.name = namespace['name']
Armin Ronacher64b08a02010-03-12 03:17:41 +0100791 t.filename = namespace['__file__']
Armin Ronacher7259c762008-04-30 13:03:59 +0200792 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200793
Georg Brandl3e497b72008-09-19 09:55:17 +0000794 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200795 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200796 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200797
798 # debug and loader helpers
799 t._debug_info = namespace['debug_info']
Armin Ronacher64b08a02010-03-12 03:17:41 +0100800 t._uptodate = None
801
802 # store the reference
803 namespace['environment'] = environment
804 namespace['__jinja_template__'] = t
Armin Ronacher7259c762008-04-30 13:03:59 +0200805
806 return t
807
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200808 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200809 """This method accepts the same arguments as the `dict` constructor:
810 A dict, a dict subclass or some keyword arguments. If no arguments
811 are given the context will be empty. These two calls do the same::
812
813 template.render(knights='that say nih')
814 template.render({'knights': 'that say nih'})
815
816 This will return the rendered template as unicode string.
817 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200818 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200819 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200820 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200821 except:
Armin Ronacherbd357722009-08-05 20:25:06 +0200822 exc_info = sys.exc_info()
823 return self.environment.handle_exception(exc_info, True)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200824
825 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200826 """Works exactly like :meth:`generate` but returns a
827 :class:`TemplateStream`.
828 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200829 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200830
831 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200832 """For very large templates it can be useful to not render the whole
833 template at once but evaluate each statement after another and yield
834 piece for piece. This method basically does exactly that and returns
835 a generator that yields one item after another as unicode strings.
836
837 It accepts the same arguments as :meth:`render`.
838 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200839 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200840 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200841 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200842 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200843 except:
Armin Ronacherbd357722009-08-05 20:25:06 +0200844 exc_info = sys.exc_info()
845 else:
846 return
847 yield self.environment.handle_exception(exc_info, True)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200848
Armin Ronacher673aa882008-10-04 18:06:57 +0200849 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200850 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200851 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200852 are added to the context. If shared is set to `True` the data
853 is passed as it to the context without adding the globals.
854
855 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200856 """
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100857 return new_context(self.environment, self.name, self.blocks,
858 vars, shared, self.globals, locals)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200859
Armin Ronacher673aa882008-10-04 18:06:57 +0200860 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200861 """This method works like the :attr:`module` attribute when called
Armin Ronacher0aa0f582009-03-18 01:01:36 +0100862 without arguments but it will evaluate the template on every call
863 rather than caching it. It's also possible to provide
Armin Ronacher7ceced52008-05-03 10:15:31 +0200864 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200865 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200866 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200867 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200868
Armin Ronacherd84ec462008-04-29 13:43:16 +0200869 @property
870 def module(self):
871 """The template as module. This is used for imports in the
872 template runtime but is also useful if one wants to access
873 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200874
Armin Ronacherd84ec462008-04-29 13:43:16 +0200875 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
876 >>> unicode(t.module)
877 u'23'
878 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200879 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200880 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200881 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200882 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200883 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200884 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200885
Armin Ronacherba3757b2008-04-16 19:43:16 +0200886 def get_corresponding_lineno(self, lineno):
887 """Return the source line number of a line number in the
888 generated bytecode as they are not in sync.
889 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200890 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200891 if code_line <= lineno:
892 return template_line
893 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200894
Armin Ronacher9a822052008-04-17 18:44:07 +0200895 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200896 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200897 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200898 if self._uptodate is None:
899 return True
900 return self._uptodate()
901
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200902 @property
903 def debug_info(self):
904 """The debug info mapping."""
905 return [tuple(map(int, x.split('='))) for x in
906 self._debug_info.split('&')]
907
Armin Ronacherc63243e2008-04-14 22:53:58 +0200908 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200909 if self.name is None:
910 name = 'memory:%x' % id(self)
911 else:
912 name = repr(self.name)
913 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200914
915
Armin Ronacherd84ec462008-04-29 13:43:16 +0200916class TemplateModule(object):
917 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200918 template are available as attributes on this object. Additionally
919 converting it into an unicode- or bytestrings renders the contents.
920 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200921
922 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200923 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200924 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200925 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200926
Armin Ronacher0faa8612010-02-09 15:04:51 +0100927 def __html__(self):
928 return Markup(concat(self._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200929
930 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200931 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200932
Armin Ronacheracbd4082010-02-10 00:07:43 +0100933 # unicode goes after __str__ because we configured 2to3 to rename
934 # __unicode__ to __str__. because the 2to3 tree is not designed to
935 # remove nodes from it, we leave the above __str__ around and let
936 # it override at runtime.
Armin Ronacher790b8a82010-02-10 00:05:46 +0100937 def __unicode__(self):
938 return concat(self._body_stream)
939
Armin Ronacher963f97d2008-04-25 11:44:59 +0200940 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200941 if self.__name__ is None:
942 name = 'memory:%x' % id(self)
943 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200944 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200945 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200946
947
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100948class TemplateExpression(object):
949 """The :meth:`jinja2.Environment.compile_expression` method returns an
950 instance of this object. It encapsulates the expression-like access
951 to the template with an expression it wraps.
952 """
953
954 def __init__(self, template, undefined_to_none):
955 self._template = template
956 self._undefined_to_none = undefined_to_none
957
958 def __call__(self, *args, **kwargs):
959 context = self._template.new_context(dict(*args, **kwargs))
960 consume(self._template.root_render_func(context))
961 rv = context.vars['result']
962 if self._undefined_to_none and isinstance(rv, Undefined):
963 rv = None
964 return rv
965
966
Armin Ronacherc63243e2008-04-14 22:53:58 +0200967class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200968 """A template stream works pretty much like an ordinary python generator
969 but it can buffer multiple items to reduce the number of total iterations.
970 Per default the output is unbuffered which means that for every unbuffered
971 instruction in the template one unicode string is yielded.
972
973 If buffering is enabled with a buffer size of 5, five items are combined
974 into a new unicode string. This is mainly useful if you are streaming
975 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200976 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200977
978 def __init__(self, gen):
979 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200980 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200981
Armin Ronacher74b51062008-06-17 11:28:59 +0200982 def dump(self, fp, encoding=None, errors='strict'):
983 """Dump the complete stream into a file or file-like object.
984 Per default unicode strings are written, if you want to encode
985 before writing specifiy an `encoding`.
986
987 Example usage::
988
989 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
990 """
991 close = False
992 if isinstance(fp, basestring):
993 fp = file(fp, 'w')
994 close = True
995 try:
996 if encoding is not None:
997 iterable = (x.encode(encoding, errors) for x in self)
998 else:
999 iterable = self
1000 if hasattr(fp, 'writelines'):
1001 fp.writelines(iterable)
1002 else:
1003 for item in iterable:
1004 fp.write(item)
1005 finally:
1006 if close:
1007 fp.close()
1008
Armin Ronacherc63243e2008-04-14 22:53:58 +02001009 def disable_buffering(self):
1010 """Disable the output buffering."""
1011 self._next = self._gen.next
1012 self.buffered = False
1013
1014 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +02001015 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +02001016 if size <= 1:
1017 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +02001018
Armin Ronacher5dfbfc12008-05-25 18:10:12 +02001019 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +02001020 buf = []
1021 c_size = 0
1022 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +02001023
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001024 while 1:
1025 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +02001026 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +02001027 c = next()
1028 push(c)
1029 if c:
1030 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001031 except StopIteration:
1032 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +02001033 return
Armin Ronacherde6bf712008-04-26 01:44:14 +02001034 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001035 del buf[:]
1036 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +02001037
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001038 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +02001039 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +02001040
1041 def __iter__(self):
1042 return self
1043
1044 def next(self):
1045 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +02001046
1047
1048# hook in default template class. if anyone reads this comment: ignore that
1049# it's possible to use custom templates ;-)
1050Environment.template_class = Template