blob: 519e9ecf5266e290927e2c2f0095f16af010eff2 [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 Ronacher19cf9c22008-05-01 12:49:53 +02008 :copyright: 2008 by Armin Ronacher.
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 Ronacher7259c762008-04-30 13:03:59 +020012from jinja2.defaults import *
Armin Ronacher9a0078d2008-08-13 18:24:17 +020013from jinja2.lexer import get_lexer, TokenStream
Armin Ronacher05530932008-04-20 13:27:49 +020014from jinja2.parser import Parser
Armin Ronacherbcb7c532008-04-11 16:30:34 +020015from jinja2.optimizer import optimize
16from jinja2.compiler import generate
Armin Ronacher7ceced52008-05-03 10:15:31 +020017from jinja2.runtime import Undefined, Context
Armin Ronacheraaf010d2008-05-01 13:14:30 +020018from jinja2.exceptions import TemplateSyntaxError
Armin Ronacher7ceced52008-05-03 10:15:31 +020019from jinja2.utils import import_string, LRUCache, Markup, missing, concat
Armin Ronacher07bc6842008-03-31 14:18:49 +020020
21
Armin Ronacher203bfcb2008-04-24 21:54:44 +020022# for direct template usage we have up to ten living environments
23_spontaneous_environments = LRUCache(10)
24
25
Armin Ronacherb5124e62008-04-25 00:36:14 +020026def get_spontaneous_environment(*args):
Georg Brandl3e497b72008-09-19 09:55:17 +000027 """Return a new spontaneous environment. A spontaneous environment is an
28 unnamed and unaccessible (in theory) environment that is used for
29 templates generated from a string and not from the file system.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020030 """
31 try:
32 env = _spontaneous_environments.get(args)
33 except TypeError:
34 return Environment(*args)
35 if env is not None:
36 return env
37 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020038 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020039 return env
40
41
Armin Ronacher7259c762008-04-30 13:03:59 +020042def create_cache(size):
43 """Return the cache class for the given size."""
44 if size == 0:
45 return None
46 if size < 0:
47 return {}
48 return LRUCache(size)
49
50
Armin Ronacherccae0552008-10-05 23:08:58 +020051def copy_cache(cache):
52 """Create an empty copy of the given cache."""
53 if cache is None:
54 return Noe
55 elif type(cache) is dict:
56 return {}
57 return LRUCache(cache.capacity)
58
59
Armin Ronacher7259c762008-04-30 13:03:59 +020060def load_extensions(environment, extensions):
61 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020062 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020063 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020064 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020065 for extension in extensions:
66 if isinstance(extension, basestring):
67 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020068 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020069 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020070
Armin Ronacher203bfcb2008-04-24 21:54:44 +020071
Armin Ronacher7259c762008-04-30 13:03:59 +020072def _environment_sanity_check(environment):
73 """Perform a sanity check on the environment."""
74 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
75 'be a subclass of undefined because filters depend on it.'
76 assert environment.block_start_string != \
77 environment.variable_start_string != \
78 environment.comment_start_string, 'block, variable and comment ' \
79 'start strings must be different'
Armin Ronacherf3c35c42008-05-23 23:18:14 +020080 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
81 'newline_sequence set to unknown line ending string.'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020082 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020083
84
Armin Ronacher07bc6842008-03-31 14:18:49 +020085class Environment(object):
Armin Ronacherf3c35c42008-05-23 23:18:14 +020086 r"""The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020087 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020088 globals and others. Instances of this class may be modified if
89 they are not shared and if no template was loaded so far.
90 Modifications on environments after the first template was loaded
91 will lead to surprising effects and undefined behavior.
92
93 Here the possible initialization parameters:
94
Armin Ronacher7b5680c2008-05-06 16:54:22 +020095 `block_start_string`
96 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020097
Armin Ronacher7b5680c2008-05-06 16:54:22 +020098 `block_end_string`
99 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200100
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200101 `variable_start_string`
102 The string marking the begin of a print statement.
103 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +0200104
Armin Ronacher63fd7982008-06-20 18:47:56 +0200105 `variable_end_string`
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200106 The string marking the end of a print statement. Defaults to
107 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200108
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200109 `comment_start_string`
110 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200111
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200112 `comment_end_string`
113 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200114
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200115 `line_statement_prefix`
116 If given and a string, this will be used as prefix for line based
117 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200118
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200119 `trim_blocks`
120 If this is set to ``True`` the first newline after a block is
121 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200122
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200123 `newline_sequence`
124 The sequence that starts a newline. Must be one of ``'\r'``,
125 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
126 useful default for Linux and OS X systems as well as web
127 applications.
128
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200129 `extensions`
130 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200131 as strings or extension classes. For more information have a
132 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200133
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200134 `optimized`
135 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200136
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200137 `undefined`
138 :class:`Undefined` or a subclass of it that is used to represent
139 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200140
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200141 `finalize`
142 A callable that finalizes the variable. Per default no finalizing
143 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200144
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200145 `autoescape`
146 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200147 For more details about auto escaping see
148 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200149
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200150 `loader`
151 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200152
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200153 `cache_size`
154 The size of the cache. Per default this is ``50`` which means
155 that if more than 50 templates are loaded the loader will clean
156 out the least recently used template. If the cache size is set to
157 ``0`` templates are recompiled all the time, if the cache size is
158 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200159
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200160 `auto_reload`
161 Some loaders load templates from locations where the template
162 sources may change (ie: file system or database). If
163 `auto_reload` is set to `True` (default) every time a template is
164 requested the loader checks if the source changed and if yes, it
165 will reload the template. For higher performance it's possible to
166 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200167
168 `bytecode_cache`
169 If set to a bytecode cache object, this object will provide a
170 cache for the internal Jinja bytecode so that templates don't
171 have to be parsed if they were not changed.
Armin Ronachera816bf42008-09-17 21:28:01 +0200172
173 See :ref:`bytecode-cache` for more information.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200174 """
175
Armin Ronacherc63243e2008-04-14 22:53:58 +0200176 #: if this environment is sandboxed. Modifying this variable won't make
177 #: the environment sandboxed though. For a real sandboxed environment
178 #: have a look at jinja2.sandbox
179 sandboxed = False
180
Armin Ronacher7259c762008-04-30 13:03:59 +0200181 #: True if the environment is just an overlay
182 overlay = False
183
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200184 #: the environment this environment is linked to if it is an overlay
185 linked_to = None
186
Armin Ronacherc9705c22008-04-27 21:28:03 +0200187 #: shared environments have this set to `True`. A shared environment
188 #: must not be modified
189 shared = False
190
Armin Ronacher07bc6842008-03-31 14:18:49 +0200191 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200192 block_start_string=BLOCK_START_STRING,
193 block_end_string=BLOCK_END_STRING,
194 variable_start_string=VARIABLE_START_STRING,
195 variable_end_string=VARIABLE_END_STRING,
196 comment_start_string=COMMENT_START_STRING,
197 comment_end_string=COMMENT_END_STRING,
198 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200199 trim_blocks=TRIM_BLOCKS,
200 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200201 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200202 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200203 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200204 finalize=None,
205 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200206 loader=None,
207 cache_size=50,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200208 auto_reload=True,
209 bytecode_cache=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200210 # !!Important notice!!
211 # The constructor accepts quite a few arguments that should be
212 # passed by keyword rather than position. However it's important to
213 # not change the order of arguments because it's used at least
214 # internally in those cases:
215 # - spontaneus environments (i18n extension and Template)
216 # - unittests
217 # If parameter changes are required only add parameters at the end
218 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200219 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200220
221 # lexer / parser information
222 self.block_start_string = block_start_string
223 self.block_end_string = block_end_string
224 self.variable_start_string = variable_start_string
225 self.variable_end_string = variable_end_string
226 self.comment_start_string = comment_start_string
227 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200228 self.line_statement_prefix = line_statement_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200229 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200230 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200231
Armin Ronacherf59bac22008-04-20 13:11:43 +0200232 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200233 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200234 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200235 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200236 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200237
238 # defaults
239 self.filters = DEFAULT_FILTERS.copy()
240 self.tests = DEFAULT_TESTS.copy()
241 self.globals = DEFAULT_NAMESPACE.copy()
242
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200243 # set the loader provided
244 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200245 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200246 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200247 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200248 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200249
Armin Ronacherb5124e62008-04-25 00:36:14 +0200250 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200251 self.extensions = load_extensions(self, extensions)
252
253 _environment_sanity_check(self)
254
Armin Ronacher762079c2008-05-08 23:57:56 +0200255 def extend(self, **attributes):
256 """Add the items to the instance of the environment if they do not exist
257 yet. This is used by :ref:`extensions <writing-extensions>` to register
258 callbacks and configuration values without breaking inheritance.
259 """
260 for key, value in attributes.iteritems():
261 if not hasattr(self, key):
262 setattr(self, key, value)
263
Armin Ronacher7259c762008-04-30 13:03:59 +0200264 def overlay(self, block_start_string=missing, block_end_string=missing,
265 variable_start_string=missing, variable_end_string=missing,
266 comment_start_string=missing, comment_end_string=missing,
267 line_statement_prefix=missing, trim_blocks=missing,
268 extensions=missing, optimized=missing, undefined=missing,
269 finalize=missing, autoescape=missing, loader=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200270 cache_size=missing, auto_reload=missing,
271 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200272 """Create a new overlay environment that shares all the data with the
273 current environment except of cache and the overriden attributes.
274 Extensions cannot be removed for a overlayed environment. A overlayed
275 environment automatically gets all the extensions of the environment it
276 is linked to plus optional extra extensions.
277
278 Creating overlays should happen after the initial environment was set
279 up completely. Not all attributes are truly linked, some are just
280 copied over so modifications on the original environment may not shine
281 through.
282 """
283 args = dict(locals())
284 del args['self'], args['cache_size'], args['extensions']
285
286 rv = object.__new__(self.__class__)
287 rv.__dict__.update(self.__dict__)
288 rv.overlay = True
289 rv.linked_to = self
290
291 for key, value in args.iteritems():
292 if value is not missing:
293 setattr(rv, key, value)
294
295 if cache_size is not missing:
296 rv.cache = create_cache(cache_size)
Armin Ronacherccae0552008-10-05 23:08:58 +0200297 else:
298 rv.cache = copy_cache(self.cache)
Armin Ronacher7259c762008-04-30 13:03:59 +0200299
Armin Ronacher023b5e92008-05-08 11:03:10 +0200300 rv.extensions = {}
301 for key, value in self.extensions.iteritems():
302 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200303 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200304 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200305
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200306 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200307
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200308 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200309
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200310 def getitem(self, obj, argument):
311 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200312 try:
313 return obj[argument]
314 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200315 if isinstance(argument, basestring):
316 try:
317 attr = str(argument)
318 except:
319 pass
320 else:
321 try:
322 return getattr(obj, attr)
323 except AttributeError:
324 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200325 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200326
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200327 def getattr(self, obj, attribute):
328 """Get an item or attribute of an object but prefer the attribute.
329 Unlike :meth:`getitem` the attribute *must* be a bytestring.
330 """
331 try:
332 return getattr(obj, attribute)
333 except AttributeError:
334 pass
335 try:
336 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200337 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200338 return self.undefined(obj=obj, name=attribute)
339
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200340 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200341 """Parse the sourcecode and return the abstract syntax tree. This
342 tree of nodes is used by the compiler to convert the template into
343 executable source- or bytecode. This is useful for debugging or to
344 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200345
346 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
347 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200348 """
Armin Ronacher67fdddf2008-05-16 09:27:51 +0200349 if isinstance(filename, unicode):
350 filename = filename.encode('utf-8')
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200351 try:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200352 return Parser(self, source, name, filename).parse()
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200353 except TemplateSyntaxError, e:
Armin Ronacherccae0552008-10-05 23:08:58 +0200354 e.source = source
355 raise e
Armin Ronacher07bc6842008-03-31 14:18:49 +0200356
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200357 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200358 """Lex the given sourcecode and return a generator that yields
359 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200360 This can be useful for :ref:`extension development <writing-extensions>`
361 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200362
363 This does not perform preprocessing. If you want the preprocessing
364 of the extensions to be applied you have to filter source through
365 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200366 """
Armin Ronacherccae0552008-10-05 23:08:58 +0200367 source = unicode(source)
368 try:
369 return self.lexer.tokeniter(source, name, filename)
370 except TemplateSyntaxError, e:
371 e.source = source
372 raise e
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200373
374 def preprocess(self, source, name=None, filename=None):
375 """Preprocesses the source with all extensions. This is automatically
376 called for all parsing and compiling methods but *not* for :meth:`lex`
377 because there you usually only want the actual source tokenized.
378 """
379 return reduce(lambda s, e: e.preprocess(s, name, filename),
380 self.extensions.itervalues(), unicode(source))
381
382 def _tokenize(self, source, name, filename=None):
383 """Called by the parser to do the preprocessing and filtering
384 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
385 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200386 source = self.preprocess(source, name, filename)
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200387 stream = self.lexer.tokenize(source, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200388 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200389 stream = ext.filter_stream(stream)
390 if not isinstance(stream, TokenStream):
391 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200392 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200393
Armin Ronacher981cbf62008-05-13 09:12:27 +0200394 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200395 """Compile a node or template source code. The `name` parameter is
396 the load name of the template after it was joined using
397 :meth:`join_path` if necessary, not the filename on the file system.
398 the `filename` parameter is the estimated filename of the template on
399 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200400 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200401
402 The return value of this method is a python code object. If the `raw`
403 parameter is `True` the return value will be a string with python
404 code equivalent to the bytecode returned otherwise. This method is
405 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200406 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200407 if isinstance(source, basestring):
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200408 source = self.parse(source, name, filename)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200409 if self.optimized:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200410 node = optimize(source, self)
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200411 source = generate(node, self, name, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200412 if raw:
413 return source
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200414 if filename is None:
Armin Ronacher68f77672008-04-17 11:50:39 +0200415 filename = '<template>'
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200416 elif isinstance(filename, unicode):
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200417 filename = filename.encode('utf-8')
418 return compile(source, filename, 'exec')
419
420 def join_path(self, template, parent):
421 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200422 relative to the loader root so this method returns the `template`
423 parameter unchanged, but if the paths should be relative to the
424 parent template, this function can be used to calculate the real
425 template name.
426
427 Subclasses may override this method and implement template path
428 joining here.
429 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200430 return template
431
Armin Ronacherfed44b52008-04-13 19:42:53 +0200432 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200433 """Load a template from the loader. If a loader is configured this
434 method ask the loader for the template and returns a :class:`Template`.
435 If the `parent` parameter is not `None`, :meth:`join_path` is called
436 to get the real template name before loading.
437
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200438 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200439 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200440
441 If the template does not exist a :exc:`TemplateNotFound` exception is
442 raised.
443 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200444 if self.loader is None:
445 raise TypeError('no loader for this environment specified')
446 if parent is not None:
447 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200448
449 if self.cache is not None:
450 template = self.cache.get(name)
451 if template is not None and (not self.auto_reload or \
452 template.is_up_to_date):
453 return template
454
455 template = self.loader.load(self, name, self.make_globals(globals))
456 if self.cache is not None:
457 self.cache[name] = template
458 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200459
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200460 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200461 """Load a template from a string. This parses the source given and
462 returns a :class:`Template` object.
463 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200464 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200465 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200466 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200467
468 def make_globals(self, d):
469 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200470 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200471 return self.globals
472 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200473
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200474
475class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200476 """The central template object. This class represents a compiled template
477 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200478
Armin Ronacherd1342312008-04-28 12:20:12 +0200479 Normally the template object is generated from an :class:`Environment` but
480 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200481 instance directly using the constructor. It takes the same arguments as
482 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200483
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200484 Every template object has a few methods and members that are guaranteed
485 to exist. However it's important that a template object should be
486 considered immutable. Modifications on the object are not supported.
487
488 Template objects created from the constructor rather than an environment
489 do have an `environment` attribute that points to a temporary environment
490 that is probably shared with other templates created with the constructor
491 and compatible settings.
492
493 >>> template = Template('Hello {{ name }}!')
494 >>> template.render(name='John Doe')
495 u'Hello John Doe!'
496
497 >>> stream = template.stream(name='John Doe')
498 >>> stream.next()
499 u'Hello John Doe!'
500 >>> stream.next()
501 Traceback (most recent call last):
502 ...
503 StopIteration
504 """
505
506 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200507 block_start_string=BLOCK_START_STRING,
508 block_end_string=BLOCK_END_STRING,
509 variable_start_string=VARIABLE_START_STRING,
510 variable_end_string=VARIABLE_END_STRING,
511 comment_start_string=COMMENT_START_STRING,
512 comment_end_string=COMMENT_END_STRING,
513 line_statement_prefix=LINE_STATEMENT_PREFIX,
514 trim_blocks=TRIM_BLOCKS,
515 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200516 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200517 optimized=True,
518 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200519 finalize=None,
520 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200521 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200522 block_start_string, block_end_string, variable_start_string,
523 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200524 line_statement_prefix, trim_blocks, newline_sequence,
525 frozenset(extensions), optimized, undefined, finalize,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200526 autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200527 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200528
Armin Ronacher7259c762008-04-30 13:03:59 +0200529 @classmethod
530 def from_code(cls, environment, code, globals, uptodate=None):
531 """Creates a template object from compiled code and the globals. This
532 is used by the loaders and environment to create a template object.
533 """
534 t = object.__new__(cls)
535 namespace = {
536 'environment': environment,
537 '__jinja_template__': t
538 }
539 exec code in namespace
540 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200541 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200542 t.name = namespace['name']
543 t.filename = code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200544 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200545
Georg Brandl3e497b72008-09-19 09:55:17 +0000546 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200547 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200548 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200549
550 # debug and loader helpers
551 t._debug_info = namespace['debug_info']
552 t._uptodate = uptodate
553
554 return t
555
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200556 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200557 """This method accepts the same arguments as the `dict` constructor:
558 A dict, a dict subclass or some keyword arguments. If no arguments
559 are given the context will be empty. These two calls do the same::
560
561 template.render(knights='that say nih')
562 template.render({'knights': 'that say nih'})
563
564 This will return the rendered template as unicode string.
565 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200566 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200567 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200568 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200569 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200570 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200571 exc_type, exc_value, tb = translate_exception(sys.exc_info())
572 raise exc_type, exc_value, tb
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200573
574 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200575 """Works exactly like :meth:`generate` but returns a
576 :class:`TemplateStream`.
577 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200578 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200579
580 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200581 """For very large templates it can be useful to not render the whole
582 template at once but evaluate each statement after another and yield
583 piece for piece. This method basically does exactly that and returns
584 a generator that yields one item after another as unicode strings.
585
586 It accepts the same arguments as :meth:`render`.
587 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200588 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200589 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200590 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200591 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200592 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200593 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200594 exc_type, exc_value, tb = translate_exception(sys.exc_info())
595 raise exc_type, exc_value, tb
596
Armin Ronacher673aa882008-10-04 18:06:57 +0200597 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200598 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200599 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200600 are added to the context. If shared is set to `True` the data
601 is passed as it to the context without adding the globals.
602
603 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200604 """
605 if vars is None:
606 vars = {}
607 if shared:
608 parent = vars
609 else:
610 parent = dict(self.globals, **vars)
Armin Ronacher673aa882008-10-04 18:06:57 +0200611 if locals:
Armin Ronacherccae0552008-10-05 23:08:58 +0200612 # if the parent is shared a copy should be created because
613 # we don't want to modify the dict passed
Armin Ronacher673aa882008-10-04 18:06:57 +0200614 if shared:
615 parent = dict(parent)
616 for key, value in locals.iteritems():
617 if key[:2] == 'l_' and value is not missing:
618 parent[key[2:]] = value
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200619 return Context(self.environment, parent, self.name, self.blocks)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200620
Armin Ronacher673aa882008-10-04 18:06:57 +0200621 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200622 """This method works like the :attr:`module` attribute when called
623 without arguments but it will evaluate the template every call
624 rather then caching the template. It's also possible to provide
625 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200626 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200627 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200628 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200629
Armin Ronacherd84ec462008-04-29 13:43:16 +0200630 @property
631 def module(self):
632 """The template as module. This is used for imports in the
633 template runtime but is also useful if one wants to access
634 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200635
Armin Ronacherd84ec462008-04-29 13:43:16 +0200636 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
637 >>> unicode(t.module)
638 u'23'
639 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200640 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200641 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200642 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200643 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200644 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200645 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200646
Armin Ronacherba3757b2008-04-16 19:43:16 +0200647 def get_corresponding_lineno(self, lineno):
648 """Return the source line number of a line number in the
649 generated bytecode as they are not in sync.
650 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200651 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200652 if code_line <= lineno:
653 return template_line
654 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200655
Armin Ronacher9a822052008-04-17 18:44:07 +0200656 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200657 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200658 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200659 if self._uptodate is None:
660 return True
661 return self._uptodate()
662
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200663 @property
664 def debug_info(self):
665 """The debug info mapping."""
666 return [tuple(map(int, x.split('='))) for x in
667 self._debug_info.split('&')]
668
Armin Ronacherc63243e2008-04-14 22:53:58 +0200669 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200670 if self.name is None:
671 name = 'memory:%x' % id(self)
672 else:
673 name = repr(self.name)
674 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200675
676
Armin Ronacherd84ec462008-04-29 13:43:16 +0200677class TemplateModule(object):
678 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200679 template are available as attributes on this object. Additionally
680 converting it into an unicode- or bytestrings renders the contents.
681 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200682
683 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200684 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200685 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200686 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200687
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200688 __unicode__ = lambda x: concat(x._body_stream)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200689 __html__ = lambda x: Markup(concat(x._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200690
691 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200692 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200693
694 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200695 if self.__name__ is None:
696 name = 'memory:%x' % id(self)
697 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200698 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200699 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200700
701
Armin Ronacherc63243e2008-04-14 22:53:58 +0200702class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200703 """A template stream works pretty much like an ordinary python generator
704 but it can buffer multiple items to reduce the number of total iterations.
705 Per default the output is unbuffered which means that for every unbuffered
706 instruction in the template one unicode string is yielded.
707
708 If buffering is enabled with a buffer size of 5, five items are combined
709 into a new unicode string. This is mainly useful if you are streaming
710 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200711 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200712
713 def __init__(self, gen):
714 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200715 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200716
Armin Ronacher74b51062008-06-17 11:28:59 +0200717 def dump(self, fp, encoding=None, errors='strict'):
718 """Dump the complete stream into a file or file-like object.
719 Per default unicode strings are written, if you want to encode
720 before writing specifiy an `encoding`.
721
722 Example usage::
723
724 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
725 """
726 close = False
727 if isinstance(fp, basestring):
728 fp = file(fp, 'w')
729 close = True
730 try:
731 if encoding is not None:
732 iterable = (x.encode(encoding, errors) for x in self)
733 else:
734 iterable = self
735 if hasattr(fp, 'writelines'):
736 fp.writelines(iterable)
737 else:
738 for item in iterable:
739 fp.write(item)
740 finally:
741 if close:
742 fp.close()
743
Armin Ronacherc63243e2008-04-14 22:53:58 +0200744 def disable_buffering(self):
745 """Disable the output buffering."""
746 self._next = self._gen.next
747 self.buffered = False
748
749 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200750 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200751 if size <= 1:
752 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200753
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200754 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200755 buf = []
756 c_size = 0
757 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +0200758
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200759 while 1:
760 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200761 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200762 c = next()
763 push(c)
764 if c:
765 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200766 except StopIteration:
767 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200768 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200769 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200770 del buf[:]
771 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200772
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200773 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200774 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200775
776 def __iter__(self):
777 return self
778
779 def next(self):
780 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200781
782
783# hook in default template class. if anyone reads this comment: ignore that
784# it's possible to use custom templates ;-)
785Environment.template_class = Template