blob: 9d43339a3f85d91fb1f4e40e3aaa09e18e32e947 [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 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 Ronacher7ceced52008-05-03 10:15:31 +020018from jinja2.runtime import Undefined, Context
Armin Ronacheraaf010d2008-05-01 13:14:30 +020019from jinja2.exceptions import TemplateSyntaxError
Armin Ronacherba6e25a2008-11-02 15:58:14 +010020from jinja2.utils import import_string, LRUCache, Markup, missing, \
21 concat, consume
Armin Ronacher07bc6842008-03-31 14:18:49 +020022
23
Armin Ronacher203bfcb2008-04-24 21:54:44 +020024# for direct template usage we have up to ten living environments
25_spontaneous_environments = LRUCache(10)
26
27
Armin Ronacherb5124e62008-04-25 00:36:14 +020028def get_spontaneous_environment(*args):
Georg Brandl3e497b72008-09-19 09:55:17 +000029 """Return a new spontaneous environment. A spontaneous environment is an
30 unnamed and unaccessible (in theory) environment that is used for
31 templates generated from a string and not from the file system.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020032 """
33 try:
34 env = _spontaneous_environments.get(args)
35 except TypeError:
36 return Environment(*args)
37 if env is not None:
38 return env
39 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020040 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020041 return env
42
43
Armin Ronacher7259c762008-04-30 13:03:59 +020044def create_cache(size):
45 """Return the cache class for the given size."""
46 if size == 0:
47 return None
48 if size < 0:
49 return {}
50 return LRUCache(size)
51
52
Armin Ronacherccae0552008-10-05 23:08:58 +020053def copy_cache(cache):
54 """Create an empty copy of the given cache."""
55 if cache is None:
Armin Ronacher2bc1ef72008-12-08 15:21:26 +010056 return None
Armin Ronacherccae0552008-10-05 23:08:58 +020057 elif type(cache) is dict:
58 return {}
59 return LRUCache(cache.capacity)
60
61
Armin Ronacher7259c762008-04-30 13:03:59 +020062def load_extensions(environment, extensions):
63 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020064 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020065 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020066 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020067 for extension in extensions:
68 if isinstance(extension, basestring):
69 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020070 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020071 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020072
Armin Ronacher203bfcb2008-04-24 21:54:44 +020073
Armin Ronacher7259c762008-04-30 13:03:59 +020074def _environment_sanity_check(environment):
75 """Perform a sanity check on the environment."""
76 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
77 'be a subclass of undefined because filters depend on it.'
78 assert environment.block_start_string != \
79 environment.variable_start_string != \
80 environment.comment_start_string, 'block, variable and comment ' \
81 'start strings must be different'
Armin Ronacherf3c35c42008-05-23 23:18:14 +020082 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
83 'newline_sequence set to unknown line ending string.'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020084 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020085
86
Armin Ronacher07bc6842008-03-31 14:18:49 +020087class Environment(object):
Armin Ronacherf3c35c42008-05-23 23:18:14 +020088 r"""The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020089 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020090 globals and others. Instances of this class may be modified if
91 they are not shared and if no template was loaded so far.
92 Modifications on environments after the first template was loaded
93 will lead to surprising effects and undefined behavior.
94
95 Here the possible initialization parameters:
96
Armin Ronacher7b5680c2008-05-06 16:54:22 +020097 `block_start_string`
98 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020099
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200100 `block_end_string`
101 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200102
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200103 `variable_start_string`
104 The string marking the begin of a print statement.
105 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +0200106
Armin Ronacher63fd7982008-06-20 18:47:56 +0200107 `variable_end_string`
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200108 The string marking the end of a print statement. Defaults to
109 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200110
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200111 `comment_start_string`
112 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200113
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200114 `comment_end_string`
115 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200116
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200117 `line_statement_prefix`
118 If given and a string, this will be used as prefix for line based
119 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200120
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200121 `trim_blocks`
122 If this is set to ``True`` the first newline after a block is
123 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200124
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200125 `newline_sequence`
126 The sequence that starts a newline. Must be one of ``'\r'``,
127 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
128 useful default for Linux and OS X systems as well as web
129 applications.
130
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200131 `extensions`
132 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200133 as strings or extension classes. For more information have a
134 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200135
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200136 `optimized`
137 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200138
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200139 `undefined`
140 :class:`Undefined` or a subclass of it that is used to represent
141 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200142
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200143 `finalize`
144 A callable that finalizes the variable. Per default no finalizing
145 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200146
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200147 `autoescape`
148 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherf7e405d2008-09-08 23:57:26 +0200149 For more details about auto escaping see
150 :class:`~jinja2.utils.Markup`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200151
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200152 `loader`
153 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200154
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200155 `cache_size`
156 The size of the cache. Per default this is ``50`` which means
157 that if more than 50 templates are loaded the loader will clean
158 out the least recently used template. If the cache size is set to
159 ``0`` templates are recompiled all the time, if the cache size is
160 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200161
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200162 `auto_reload`
163 Some loaders load templates from locations where the template
164 sources may change (ie: file system or database). If
165 `auto_reload` is set to `True` (default) every time a template is
166 requested the loader checks if the source changed and if yes, it
167 will reload the template. For higher performance it's possible to
168 disable that.
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200169
170 `bytecode_cache`
171 If set to a bytecode cache object, this object will provide a
172 cache for the internal Jinja bytecode so that templates don't
173 have to be parsed if they were not changed.
Armin Ronachera816bf42008-09-17 21:28:01 +0200174
175 See :ref:`bytecode-cache` for more information.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200176 """
177
Armin Ronacherc63243e2008-04-14 22:53:58 +0200178 #: if this environment is sandboxed. Modifying this variable won't make
179 #: the environment sandboxed though. For a real sandboxed environment
180 #: have a look at jinja2.sandbox
181 sandboxed = False
182
Armin Ronacher7259c762008-04-30 13:03:59 +0200183 #: True if the environment is just an overlay
184 overlay = False
185
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200186 #: the environment this environment is linked to if it is an overlay
187 linked_to = None
188
Armin Ronacherc9705c22008-04-27 21:28:03 +0200189 #: shared environments have this set to `True`. A shared environment
190 #: must not be modified
191 shared = False
192
Armin Ronacher07bc6842008-03-31 14:18:49 +0200193 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200194 block_start_string=BLOCK_START_STRING,
195 block_end_string=BLOCK_END_STRING,
196 variable_start_string=VARIABLE_START_STRING,
197 variable_end_string=VARIABLE_END_STRING,
198 comment_start_string=COMMENT_START_STRING,
199 comment_end_string=COMMENT_END_STRING,
200 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200201 trim_blocks=TRIM_BLOCKS,
202 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200203 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200204 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200205 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200206 finalize=None,
207 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200208 loader=None,
209 cache_size=50,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200210 auto_reload=True,
211 bytecode_cache=None):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200212 # !!Important notice!!
213 # The constructor accepts quite a few arguments that should be
214 # passed by keyword rather than position. However it's important to
215 # not change the order of arguments because it's used at least
216 # internally in those cases:
217 # - spontaneus environments (i18n extension and Template)
218 # - unittests
219 # If parameter changes are required only add parameters at the end
220 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200221 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200222
223 # lexer / parser information
224 self.block_start_string = block_start_string
225 self.block_end_string = block_end_string
226 self.variable_start_string = variable_start_string
227 self.variable_end_string = variable_end_string
228 self.comment_start_string = comment_start_string
229 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200230 self.line_statement_prefix = line_statement_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200231 self.trim_blocks = trim_blocks
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200232 self.newline_sequence = newline_sequence
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200233
Armin Ronacherf59bac22008-04-20 13:11:43 +0200234 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200235 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200236 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200237 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200238 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200239
240 # defaults
241 self.filters = DEFAULT_FILTERS.copy()
242 self.tests = DEFAULT_TESTS.copy()
243 self.globals = DEFAULT_NAMESPACE.copy()
244
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200245 # set the loader provided
246 self.loader = loader
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200247 self.bytecode_cache = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200248 self.cache = create_cache(cache_size)
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200249 self.bytecode_cache = bytecode_cache
Armin Ronacher7259c762008-04-30 13:03:59 +0200250 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200251
Armin Ronacherb5124e62008-04-25 00:36:14 +0200252 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200253 self.extensions = load_extensions(self, extensions)
254
255 _environment_sanity_check(self)
256
Armin Ronacher762079c2008-05-08 23:57:56 +0200257 def extend(self, **attributes):
258 """Add the items to the instance of the environment if they do not exist
259 yet. This is used by :ref:`extensions <writing-extensions>` to register
260 callbacks and configuration values without breaking inheritance.
261 """
262 for key, value in attributes.iteritems():
263 if not hasattr(self, key):
264 setattr(self, key, value)
265
Armin Ronacher7259c762008-04-30 13:03:59 +0200266 def overlay(self, block_start_string=missing, block_end_string=missing,
267 variable_start_string=missing, variable_end_string=missing,
268 comment_start_string=missing, comment_end_string=missing,
269 line_statement_prefix=missing, trim_blocks=missing,
270 extensions=missing, optimized=missing, undefined=missing,
271 finalize=missing, autoescape=missing, loader=missing,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200272 cache_size=missing, auto_reload=missing,
273 bytecode_cache=missing):
Armin Ronacher7259c762008-04-30 13:03:59 +0200274 """Create a new overlay environment that shares all the data with the
275 current environment except of cache and the overriden attributes.
276 Extensions cannot be removed for a overlayed environment. A overlayed
277 environment automatically gets all the extensions of the environment it
278 is linked to plus optional extra extensions.
279
280 Creating overlays should happen after the initial environment was set
281 up completely. Not all attributes are truly linked, some are just
282 copied over so modifications on the original environment may not shine
283 through.
284 """
285 args = dict(locals())
286 del args['self'], args['cache_size'], args['extensions']
287
288 rv = object.__new__(self.__class__)
289 rv.__dict__.update(self.__dict__)
290 rv.overlay = True
291 rv.linked_to = self
292
293 for key, value in args.iteritems():
294 if value is not missing:
295 setattr(rv, key, value)
296
297 if cache_size is not missing:
298 rv.cache = create_cache(cache_size)
Armin Ronacherccae0552008-10-05 23:08:58 +0200299 else:
300 rv.cache = copy_cache(self.cache)
Armin Ronacher7259c762008-04-30 13:03:59 +0200301
Armin Ronacher023b5e92008-05-08 11:03:10 +0200302 rv.extensions = {}
303 for key, value in self.extensions.iteritems():
304 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200305 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200306 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200307
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200308 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200309
Armin Ronacher9a0078d2008-08-13 18:24:17 +0200310 lexer = property(get_lexer, doc="The lexer for this environment.")
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200311
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200312 def getitem(self, obj, argument):
313 """Get an item or attribute of an object but prefer the item."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200314 try:
315 return obj[argument]
316 except (TypeError, LookupError):
Armin Ronacherf15f5f72008-05-26 12:21:45 +0200317 if isinstance(argument, basestring):
318 try:
319 attr = str(argument)
320 except:
321 pass
322 else:
323 try:
324 return getattr(obj, attr)
325 except AttributeError:
326 pass
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200327 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200328
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200329 def getattr(self, obj, attribute):
330 """Get an item or attribute of an object but prefer the attribute.
331 Unlike :meth:`getitem` the attribute *must* be a bytestring.
332 """
333 try:
334 return getattr(obj, attribute)
335 except AttributeError:
336 pass
337 try:
338 return obj[attribute]
Christopher Grebsf1c940f2008-07-10 11:52:17 +0200339 except (TypeError, LookupError, AttributeError):
Armin Ronacher6dc6f292008-06-12 08:50:07 +0200340 return self.undefined(obj=obj, name=attribute)
341
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200342 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200343 """Parse the sourcecode and return the abstract syntax tree. This
344 tree of nodes is used by the compiler to convert the template into
345 executable source- or bytecode. This is useful for debugging or to
346 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200347
348 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
349 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200350 """
Armin Ronacher67fdddf2008-05-16 09:27:51 +0200351 if isinstance(filename, unicode):
352 filename = filename.encode('utf-8')
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200353 try:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200354 return Parser(self, source, name, filename).parse()
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200355 except TemplateSyntaxError, e:
Armin Ronacherccae0552008-10-05 23:08:58 +0200356 e.source = source
357 raise e
Armin Ronacher07bc6842008-03-31 14:18:49 +0200358
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200359 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200360 """Lex the given sourcecode and return a generator that yields
361 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200362 This can be useful for :ref:`extension development <writing-extensions>`
363 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200364
365 This does not perform preprocessing. If you want the preprocessing
366 of the extensions to be applied you have to filter source through
367 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200368 """
Armin Ronacherccae0552008-10-05 23:08:58 +0200369 source = unicode(source)
370 try:
371 return self.lexer.tokeniter(source, name, filename)
372 except TemplateSyntaxError, e:
373 e.source = source
374 raise e
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200375
376 def preprocess(self, source, name=None, filename=None):
377 """Preprocesses the source with all extensions. This is automatically
378 called for all parsing and compiling methods but *not* for :meth:`lex`
379 because there you usually only want the actual source tokenized.
380 """
381 return reduce(lambda s, e: e.preprocess(s, name, filename),
382 self.extensions.itervalues(), unicode(source))
383
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100384 def _tokenize(self, source, name, filename=None, state=None):
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200385 """Called by the parser to do the preprocessing and filtering
386 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
387 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200388 source = self.preprocess(source, name, filename)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100389 stream = self.lexer.tokenize(source, name, filename, state)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200390 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200391 stream = ext.filter_stream(stream)
392 if not isinstance(stream, TokenStream):
393 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200394 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200395
Armin Ronacher981cbf62008-05-13 09:12:27 +0200396 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200397 """Compile a node or template source code. The `name` parameter is
398 the load name of the template after it was joined using
399 :meth:`join_path` if necessary, not the filename on the file system.
400 the `filename` parameter is the estimated filename of the template on
401 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200402 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200403
404 The return value of this method is a python code object. If the `raw`
405 parameter is `True` the return value will be a string with python
406 code equivalent to the bytecode returned otherwise. This method is
407 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200408 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200409 if isinstance(source, basestring):
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200410 source = self.parse(source, name, filename)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200411 if self.optimized:
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100412 source = optimize(source, self)
413 source = generate(source, self, name, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200414 if raw:
415 return source
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200416 if filename is None:
Armin Ronacher68f77672008-04-17 11:50:39 +0200417 filename = '<template>'
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200418 elif isinstance(filename, unicode):
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200419 filename = filename.encode('utf-8')
420 return compile(source, filename, 'exec')
421
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100422 def compile_expression(self, source, undefined_to_none=True):
423 """A handy helper method that returns a callable that accepts keyword
424 arguments that appear as variables in the expression. If called it
425 returns the result of the expression.
426
427 This is useful if applications want to use the same rules as Jinja
428 in template "configuration files" or similar situations.
429
430 Example usage:
431
432 >>> env = Environment()
433 >>> expr = env.compile_expression('foo == 42')
434 >>> expr(foo=23)
435 False
436 >>> expr(foo=42)
437 True
438
439 Per default the return value is converted to `None` if the
440 expression returns an undefined value. This can be changed
441 by setting `undefined_to_none` to `False`.
442
443 >>> env.compile_expression('var')() is None
444 True
445 >>> env.compile_expression('var', undefined_to_none=False)()
446 Undefined
447
448 **new in Jinja 2.1**
449 """
450 parser = Parser(self, source, state='variable')
451 try:
452 expr = parser.parse_expression()
453 if not parser.stream.eos:
454 raise TemplateSyntaxError('chunk after expression',
455 parser.stream.current.lineno,
456 None, None)
457 except TemplateSyntaxError, e:
458 e.source = source
459 raise e
460 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
461 template = self.from_string(nodes.Template(body, lineno=1))
462 return TemplateExpression(template, undefined_to_none)
463
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200464 def join_path(self, template, parent):
465 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200466 relative to the loader root so this method returns the `template`
467 parameter unchanged, but if the paths should be relative to the
468 parent template, this function can be used to calculate the real
469 template name.
470
471 Subclasses may override this method and implement template path
472 joining here.
473 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200474 return template
475
Armin Ronacherfed44b52008-04-13 19:42:53 +0200476 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200477 """Load a template from the loader. If a loader is configured this
478 method ask the loader for the template and returns a :class:`Template`.
479 If the `parent` parameter is not `None`, :meth:`join_path` is called
480 to get the real template name before loading.
481
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200482 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200483 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200484
485 If the template does not exist a :exc:`TemplateNotFound` exception is
486 raised.
487 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200488 if self.loader is None:
489 raise TypeError('no loader for this environment specified')
490 if parent is not None:
491 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200492
493 if self.cache is not None:
494 template = self.cache.get(name)
495 if template is not None and (not self.auto_reload or \
496 template.is_up_to_date):
497 return template
498
499 template = self.loader.load(self, name, self.make_globals(globals))
500 if self.cache is not None:
501 self.cache[name] = template
502 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200503
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200504 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200505 """Load a template from a string. This parses the source given and
506 returns a :class:`Template` object.
507 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200508 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200509 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200510 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200511
512 def make_globals(self, d):
513 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200514 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200515 return self.globals
516 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200517
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200518
519class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200520 """The central template object. This class represents a compiled template
521 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200522
Armin Ronacherd1342312008-04-28 12:20:12 +0200523 Normally the template object is generated from an :class:`Environment` but
524 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200525 instance directly using the constructor. It takes the same arguments as
526 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200527
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200528 Every template object has a few methods and members that are guaranteed
529 to exist. However it's important that a template object should be
530 considered immutable. Modifications on the object are not supported.
531
532 Template objects created from the constructor rather than an environment
533 do have an `environment` attribute that points to a temporary environment
534 that is probably shared with other templates created with the constructor
535 and compatible settings.
536
537 >>> template = Template('Hello {{ name }}!')
538 >>> template.render(name='John Doe')
539 u'Hello John Doe!'
540
541 >>> stream = template.stream(name='John Doe')
542 >>> stream.next()
543 u'Hello John Doe!'
544 >>> stream.next()
545 Traceback (most recent call last):
546 ...
547 StopIteration
548 """
549
550 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200551 block_start_string=BLOCK_START_STRING,
552 block_end_string=BLOCK_END_STRING,
553 variable_start_string=VARIABLE_START_STRING,
554 variable_end_string=VARIABLE_END_STRING,
555 comment_start_string=COMMENT_START_STRING,
556 comment_end_string=COMMENT_END_STRING,
557 line_statement_prefix=LINE_STATEMENT_PREFIX,
558 trim_blocks=TRIM_BLOCKS,
559 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200560 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200561 optimized=True,
562 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200563 finalize=None,
564 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200565 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200566 block_start_string, block_end_string, variable_start_string,
567 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200568 line_statement_prefix, trim_blocks, newline_sequence,
569 frozenset(extensions), optimized, undefined, finalize,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200570 autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200571 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200572
Armin Ronacher7259c762008-04-30 13:03:59 +0200573 @classmethod
574 def from_code(cls, environment, code, globals, uptodate=None):
575 """Creates a template object from compiled code and the globals. This
576 is used by the loaders and environment to create a template object.
577 """
578 t = object.__new__(cls)
579 namespace = {
580 'environment': environment,
581 '__jinja_template__': t
582 }
583 exec code in namespace
584 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200585 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200586 t.name = namespace['name']
587 t.filename = code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200588 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200589
Georg Brandl3e497b72008-09-19 09:55:17 +0000590 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200591 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200592 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200593
594 # debug and loader helpers
595 t._debug_info = namespace['debug_info']
596 t._uptodate = uptodate
597
598 return t
599
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200600 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200601 """This method accepts the same arguments as the `dict` constructor:
602 A dict, a dict subclass or some keyword arguments. If no arguments
603 are given the context will be empty. These two calls do the same::
604
605 template.render(knights='that say nih')
606 template.render({'knights': 'that say nih'})
607
608 This will return the rendered template as unicode string.
609 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200610 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200611 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200612 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200613 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200614 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200615 exc_type, exc_value, tb = translate_exception(sys.exc_info())
616 raise exc_type, exc_value, tb
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200617
618 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200619 """Works exactly like :meth:`generate` but returns a
620 :class:`TemplateStream`.
621 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200622 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200623
624 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200625 """For very large templates it can be useful to not render the whole
626 template at once but evaluate each statement after another and yield
627 piece for piece. This method basically does exactly that and returns
628 a generator that yields one item after another as unicode strings.
629
630 It accepts the same arguments as :meth:`render`.
631 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200632 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200633 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200634 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200635 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200636 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200637 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200638 exc_type, exc_value, tb = translate_exception(sys.exc_info())
639 raise exc_type, exc_value, tb
640
Armin Ronacher673aa882008-10-04 18:06:57 +0200641 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200642 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200643 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200644 are added to the context. If shared is set to `True` the data
645 is passed as it to the context without adding the globals.
646
647 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200648 """
649 if vars is None:
650 vars = {}
651 if shared:
652 parent = vars
653 else:
654 parent = dict(self.globals, **vars)
Armin Ronacher673aa882008-10-04 18:06:57 +0200655 if locals:
Armin Ronacherccae0552008-10-05 23:08:58 +0200656 # if the parent is shared a copy should be created because
657 # we don't want to modify the dict passed
Armin Ronacher673aa882008-10-04 18:06:57 +0200658 if shared:
659 parent = dict(parent)
660 for key, value in locals.iteritems():
661 if key[:2] == 'l_' and value is not missing:
662 parent[key[2:]] = value
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200663 return Context(self.environment, parent, self.name, self.blocks)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200664
Armin Ronacher673aa882008-10-04 18:06:57 +0200665 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200666 """This method works like the :attr:`module` attribute when called
667 without arguments but it will evaluate the template every call
668 rather then caching the template. It's also possible to provide
669 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200670 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200671 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200672 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200673
Armin Ronacherd84ec462008-04-29 13:43:16 +0200674 @property
675 def module(self):
676 """The template as module. This is used for imports in the
677 template runtime but is also useful if one wants to access
678 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200679
Armin Ronacherd84ec462008-04-29 13:43:16 +0200680 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
681 >>> unicode(t.module)
682 u'23'
683 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200684 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200685 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200686 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200687 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200688 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200689 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200690
Armin Ronacherba3757b2008-04-16 19:43:16 +0200691 def get_corresponding_lineno(self, lineno):
692 """Return the source line number of a line number in the
693 generated bytecode as they are not in sync.
694 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200695 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200696 if code_line <= lineno:
697 return template_line
698 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200699
Armin Ronacher9a822052008-04-17 18:44:07 +0200700 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200701 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200702 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200703 if self._uptodate is None:
704 return True
705 return self._uptodate()
706
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200707 @property
708 def debug_info(self):
709 """The debug info mapping."""
710 return [tuple(map(int, x.split('='))) for x in
711 self._debug_info.split('&')]
712
Armin Ronacherc63243e2008-04-14 22:53:58 +0200713 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200714 if self.name is None:
715 name = 'memory:%x' % id(self)
716 else:
717 name = repr(self.name)
718 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200719
720
Armin Ronacherd84ec462008-04-29 13:43:16 +0200721class TemplateModule(object):
722 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200723 template are available as attributes on this object. Additionally
724 converting it into an unicode- or bytestrings renders the contents.
725 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200726
727 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200728 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200729 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200730 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200731
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200732 __unicode__ = lambda x: concat(x._body_stream)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200733 __html__ = lambda x: Markup(concat(x._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200734
735 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200736 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200737
738 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200739 if self.__name__ is None:
740 name = 'memory:%x' % id(self)
741 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200742 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200743 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200744
745
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100746class TemplateExpression(object):
747 """The :meth:`jinja2.Environment.compile_expression` method returns an
748 instance of this object. It encapsulates the expression-like access
749 to the template with an expression it wraps.
750 """
751
752 def __init__(self, template, undefined_to_none):
753 self._template = template
754 self._undefined_to_none = undefined_to_none
755
756 def __call__(self, *args, **kwargs):
757 context = self._template.new_context(dict(*args, **kwargs))
758 consume(self._template.root_render_func(context))
759 rv = context.vars['result']
760 if self._undefined_to_none and isinstance(rv, Undefined):
761 rv = None
762 return rv
763
764
Armin Ronacherc63243e2008-04-14 22:53:58 +0200765class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200766 """A template stream works pretty much like an ordinary python generator
767 but it can buffer multiple items to reduce the number of total iterations.
768 Per default the output is unbuffered which means that for every unbuffered
769 instruction in the template one unicode string is yielded.
770
771 If buffering is enabled with a buffer size of 5, five items are combined
772 into a new unicode string. This is mainly useful if you are streaming
773 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200774 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200775
776 def __init__(self, gen):
777 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200778 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200779
Armin Ronacher74b51062008-06-17 11:28:59 +0200780 def dump(self, fp, encoding=None, errors='strict'):
781 """Dump the complete stream into a file or file-like object.
782 Per default unicode strings are written, if you want to encode
783 before writing specifiy an `encoding`.
784
785 Example usage::
786
787 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
788 """
789 close = False
790 if isinstance(fp, basestring):
791 fp = file(fp, 'w')
792 close = True
793 try:
794 if encoding is not None:
795 iterable = (x.encode(encoding, errors) for x in self)
796 else:
797 iterable = self
798 if hasattr(fp, 'writelines'):
799 fp.writelines(iterable)
800 else:
801 for item in iterable:
802 fp.write(item)
803 finally:
804 if close:
805 fp.close()
806
Armin Ronacherc63243e2008-04-14 22:53:58 +0200807 def disable_buffering(self):
808 """Disable the output buffering."""
809 self._next = self._gen.next
810 self.buffered = False
811
812 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200813 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200814 if size <= 1:
815 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200816
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200817 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200818 buf = []
819 c_size = 0
820 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +0200821
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200822 while 1:
823 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200824 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200825 c = next()
826 push(c)
827 if c:
828 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200829 except StopIteration:
830 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200831 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200832 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200833 del buf[:]
834 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200835
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200836 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200837 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200838
839 def __iter__(self):
840 return self
841
842 def next(self):
843 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200844
845
846# hook in default template class. if anyone reads this comment: ignore that
847# it's possible to use custom templates ;-)
848Environment.template_class = Template