blob: c7f311ef97ea4766ca6c5ef8b386a5710cc8dca1 [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 Ronacher62ccd1b2009-01-04 14:26:19 +01008 :copyright: (c) 2009 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 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, \
Armin Ronacherd416a972009-02-24 22:58:00 +010021 concat, consume, internalcode
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 Ronacherd416a972009-02-24 22:58:00 +0100342 @internalcode
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200343 def parse(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200344 """Parse the sourcecode and return the abstract syntax tree. This
345 tree of nodes is used by the compiler to convert the template into
346 executable source- or bytecode. This is useful for debugging or to
347 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200348
349 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
350 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200351 """
Armin Ronacher67fdddf2008-05-16 09:27:51 +0200352 if isinstance(filename, unicode):
353 filename = filename.encode('utf-8')
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200354 try:
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200355 return Parser(self, source, name, filename).parse()
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200356 except TemplateSyntaxError, e:
Armin Ronacherd416a972009-02-24 22:58:00 +0100357 from jinja2.debug import translate_syntax_error
358 exc_type, exc_value, tb = translate_syntax_error(e, source)
359 raise exc_type, exc_value, tb
Armin Ronacher07bc6842008-03-31 14:18:49 +0200360
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200361 def lex(self, source, name=None, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200362 """Lex the given sourcecode and return a generator that yields
363 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200364 This can be useful for :ref:`extension development <writing-extensions>`
365 and debugging templates.
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200366
367 This does not perform preprocessing. If you want the preprocessing
368 of the extensions to be applied you have to filter source through
369 the :meth:`preprocess` method.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200370 """
Armin Ronacherccae0552008-10-05 23:08:58 +0200371 source = unicode(source)
372 try:
373 return self.lexer.tokeniter(source, name, filename)
374 except TemplateSyntaxError, e:
Armin Ronacherd416a972009-02-24 22:58:00 +0100375 from jinja2.debug import translate_syntax_error
376 exc_type, exc_value, tb = translate_syntax_error(e, source)
377 raise exc_type, exc_value, tb
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200378
379 def preprocess(self, source, name=None, filename=None):
380 """Preprocesses the source with all extensions. This is automatically
381 called for all parsing and compiling methods but *not* for :meth:`lex`
382 because there you usually only want the actual source tokenized.
383 """
384 return reduce(lambda s, e: e.preprocess(s, name, filename),
385 self.extensions.itervalues(), unicode(source))
386
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100387 def _tokenize(self, source, name, filename=None, state=None):
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200388 """Called by the parser to do the preprocessing and filtering
389 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
390 """
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200391 source = self.preprocess(source, name, filename)
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100392 stream = self.lexer.tokenize(source, name, filename, state)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200393 for ext in self.extensions.itervalues():
Armin Ronacher3e3a9be2008-06-14 12:44:15 +0200394 stream = ext.filter_stream(stream)
395 if not isinstance(stream, TokenStream):
396 stream = TokenStream(stream, name, filename)
Armin Ronacher9ad96e72008-06-13 22:44:01 +0200397 return stream
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200398
Armin Ronacherd416a972009-02-24 22:58:00 +0100399 @internalcode
Armin Ronacher981cbf62008-05-13 09:12:27 +0200400 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200401 """Compile a node or template source code. The `name` parameter is
402 the load name of the template after it was joined using
403 :meth:`join_path` if necessary, not the filename on the file system.
404 the `filename` parameter is the estimated filename of the template on
405 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200406 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200407
408 The return value of this method is a python code object. If the `raw`
409 parameter is `True` the return value will be a string with python
410 code equivalent to the bytecode returned otherwise. This method is
411 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200412 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200413 if isinstance(source, basestring):
Armin Ronacher7f15ef82008-05-16 09:11:39 +0200414 source = self.parse(source, name, filename)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200415 if self.optimized:
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100416 source = optimize(source, self)
417 source = generate(source, self, name, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200418 if raw:
419 return source
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200420 if filename is None:
Armin Ronacher68f77672008-04-17 11:50:39 +0200421 filename = '<template>'
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200422 elif isinstance(filename, unicode):
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200423 filename = filename.encode('utf-8')
424 return compile(source, filename, 'exec')
425
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100426 def compile_expression(self, source, undefined_to_none=True):
427 """A handy helper method that returns a callable that accepts keyword
428 arguments that appear as variables in the expression. If called it
429 returns the result of the expression.
430
431 This is useful if applications want to use the same rules as Jinja
432 in template "configuration files" or similar situations.
433
434 Example usage:
435
436 >>> env = Environment()
437 >>> expr = env.compile_expression('foo == 42')
438 >>> expr(foo=23)
439 False
440 >>> expr(foo=42)
441 True
442
443 Per default the return value is converted to `None` if the
444 expression returns an undefined value. This can be changed
445 by setting `undefined_to_none` to `False`.
446
447 >>> env.compile_expression('var')() is None
448 True
449 >>> env.compile_expression('var', undefined_to_none=False)()
450 Undefined
451
452 **new in Jinja 2.1**
453 """
454 parser = Parser(self, source, state='variable')
455 try:
456 expr = parser.parse_expression()
457 if not parser.stream.eos:
458 raise TemplateSyntaxError('chunk after expression',
459 parser.stream.current.lineno,
460 None, None)
461 except TemplateSyntaxError, e:
462 e.source = source
463 raise e
464 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
465 template = self.from_string(nodes.Template(body, lineno=1))
466 return TemplateExpression(template, undefined_to_none)
467
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200468 def join_path(self, template, parent):
469 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200470 relative to the loader root so this method returns the `template`
471 parameter unchanged, but if the paths should be relative to the
472 parent template, this function can be used to calculate the real
473 template name.
474
475 Subclasses may override this method and implement template path
476 joining here.
477 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200478 return template
479
Armin Ronacherd416a972009-02-24 22:58:00 +0100480 @internalcode
Armin Ronacherfed44b52008-04-13 19:42:53 +0200481 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200482 """Load a template from the loader. If a loader is configured this
483 method ask the loader for the template and returns a :class:`Template`.
484 If the `parent` parameter is not `None`, :meth:`join_path` is called
485 to get the real template name before loading.
486
Armin Ronacher7a519ee2008-09-08 23:10:47 +0200487 The `globals` parameter can be used to provide template wide globals.
Armin Ronacher981cbf62008-05-13 09:12:27 +0200488 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200489
490 If the template does not exist a :exc:`TemplateNotFound` exception is
491 raised.
492 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200493 if self.loader is None:
494 raise TypeError('no loader for this environment specified')
495 if parent is not None:
496 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200497
498 if self.cache is not None:
499 template = self.cache.get(name)
500 if template is not None and (not self.auto_reload or \
501 template.is_up_to_date):
502 return template
503
504 template = self.loader.load(self, name, self.make_globals(globals))
505 if self.cache is not None:
506 self.cache[name] = template
507 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200508
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200509 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200510 """Load a template from a string. This parses the source given and
511 returns a :class:`Template` object.
512 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200513 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200514 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200515 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200516
517 def make_globals(self, d):
518 """Return a dict for the globals."""
Armin Ronacher5411ce72008-05-25 11:36:22 +0200519 if not d:
Armin Ronacherfed44b52008-04-13 19:42:53 +0200520 return self.globals
521 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200522
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200523
524class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200525 """The central template object. This class represents a compiled template
526 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200527
Armin Ronacherd1342312008-04-28 12:20:12 +0200528 Normally the template object is generated from an :class:`Environment` but
529 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200530 instance directly using the constructor. It takes the same arguments as
531 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200532
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200533 Every template object has a few methods and members that are guaranteed
534 to exist. However it's important that a template object should be
535 considered immutable. Modifications on the object are not supported.
536
537 Template objects created from the constructor rather than an environment
538 do have an `environment` attribute that points to a temporary environment
539 that is probably shared with other templates created with the constructor
540 and compatible settings.
541
542 >>> template = Template('Hello {{ name }}!')
543 >>> template.render(name='John Doe')
544 u'Hello John Doe!'
545
546 >>> stream = template.stream(name='John Doe')
547 >>> stream.next()
548 u'Hello John Doe!'
549 >>> stream.next()
550 Traceback (most recent call last):
551 ...
552 StopIteration
553 """
554
555 def __new__(cls, source,
Armin Ronacher4f5008f2008-05-23 23:36:07 +0200556 block_start_string=BLOCK_START_STRING,
557 block_end_string=BLOCK_END_STRING,
558 variable_start_string=VARIABLE_START_STRING,
559 variable_end_string=VARIABLE_END_STRING,
560 comment_start_string=COMMENT_START_STRING,
561 comment_end_string=COMMENT_END_STRING,
562 line_statement_prefix=LINE_STATEMENT_PREFIX,
563 trim_blocks=TRIM_BLOCKS,
564 newline_sequence=NEWLINE_SEQUENCE,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200565 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200566 optimized=True,
567 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200568 finalize=None,
569 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200570 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200571 block_start_string, block_end_string, variable_start_string,
572 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200573 line_statement_prefix, trim_blocks, newline_sequence,
574 frozenset(extensions), optimized, undefined, finalize,
Armin Ronacher4d5bdff2008-09-17 16:19:46 +0200575 autoescape, None, 0, False, None)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200576 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200577
Armin Ronacher7259c762008-04-30 13:03:59 +0200578 @classmethod
579 def from_code(cls, environment, code, globals, uptodate=None):
580 """Creates a template object from compiled code and the globals. This
581 is used by the loaders and environment to create a template object.
582 """
583 t = object.__new__(cls)
584 namespace = {
585 'environment': environment,
586 '__jinja_template__': t
587 }
588 exec code in namespace
589 t.environment = environment
Armin Ronacher771c7502008-05-18 23:14:14 +0200590 t.globals = globals
Armin Ronacher7259c762008-04-30 13:03:59 +0200591 t.name = namespace['name']
592 t.filename = code.co_filename
Armin Ronacher7259c762008-04-30 13:03:59 +0200593 t.blocks = namespace['blocks']
Armin Ronacher771c7502008-05-18 23:14:14 +0200594
Georg Brandl3e497b72008-09-19 09:55:17 +0000595 # render function and module
Armin Ronacher5411ce72008-05-25 11:36:22 +0200596 t.root_render_func = namespace['root']
Armin Ronacher771c7502008-05-18 23:14:14 +0200597 t._module = None
Armin Ronacher7259c762008-04-30 13:03:59 +0200598
599 # debug and loader helpers
600 t._debug_info = namespace['debug_info']
601 t._uptodate = uptodate
602
603 return t
604
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200605 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200606 """This method accepts the same arguments as the `dict` constructor:
607 A dict, a dict subclass or some keyword arguments. If no arguments
608 are given the context will be empty. These two calls do the same::
609
610 template.render(knights='that say nih')
611 template.render({'knights': 'that say nih'})
612
613 This will return the rendered template as unicode string.
614 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200615 vars = dict(*args, **kwargs)
Armin Ronacherf41d1392008-04-18 16:41:52 +0200616 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200617 return concat(self.root_render_func(self.new_context(vars)))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200618 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200619 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200620 exc_type, exc_value, tb = translate_exception(sys.exc_info())
621 raise exc_type, exc_value, tb
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200622
623 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200624 """Works exactly like :meth:`generate` but returns a
625 :class:`TemplateStream`.
626 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200627 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200628
629 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200630 """For very large templates it can be useful to not render the whole
631 template at once but evaluate each statement after another and yield
632 piece for piece. This method basically does exactly that and returns
633 a generator that yields one item after another as unicode strings.
634
635 It accepts the same arguments as :meth:`render`.
636 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200637 vars = dict(*args, **kwargs)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200638 try:
Armin Ronacher5411ce72008-05-25 11:36:22 +0200639 for event in self.root_render_func(self.new_context(vars)):
Armin Ronacher771c7502008-05-18 23:14:14 +0200640 yield event
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200641 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200642 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200643 exc_type, exc_value, tb = translate_exception(sys.exc_info())
644 raise exc_type, exc_value, tb
645
Armin Ronacher673aa882008-10-04 18:06:57 +0200646 def new_context(self, vars=None, shared=False, locals=None):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200647 """Create a new :class:`Context` for this template. The vars
Armin Ronacherc9705c22008-04-27 21:28:03 +0200648 provided will be passed to the template. Per default the globals
Armin Ronacher673aa882008-10-04 18:06:57 +0200649 are added to the context. If shared is set to `True` the data
650 is passed as it to the context without adding the globals.
651
652 `locals` can be a dict of local variables for internal usage.
Armin Ronacherc9705c22008-04-27 21:28:03 +0200653 """
Armin Ronacher74a0cd92009-02-19 15:56:53 +0100654 return new_context(self.environment, self.name, self.blocks,
655 vars, shared, self.globals, locals)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200656
Armin Ronacher673aa882008-10-04 18:06:57 +0200657 def make_module(self, vars=None, shared=False, locals=None):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200658 """This method works like the :attr:`module` attribute when called
659 without arguments but it will evaluate the template every call
660 rather then caching the template. It's also possible to provide
661 a dict which is then used as context. The arguments are the same
Armin Ronacherf3c35c42008-05-23 23:18:14 +0200662 as for the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200663 """
Armin Ronacher673aa882008-10-04 18:06:57 +0200664 return TemplateModule(self, self.new_context(vars, shared, locals))
Armin Ronacherea847c52008-05-02 20:04:32 +0200665
Armin Ronacherd84ec462008-04-29 13:43:16 +0200666 @property
667 def module(self):
668 """The template as module. This is used for imports in the
669 template runtime but is also useful if one wants to access
670 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200671
Armin Ronacherd84ec462008-04-29 13:43:16 +0200672 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
673 >>> unicode(t.module)
674 u'23'
675 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200676 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200677 """
Armin Ronacher771c7502008-05-18 23:14:14 +0200678 if self._module is not None:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200679 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200680 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200681 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200682
Armin Ronacherba3757b2008-04-16 19:43:16 +0200683 def get_corresponding_lineno(self, lineno):
684 """Return the source line number of a line number in the
685 generated bytecode as they are not in sync.
686 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200687 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200688 if code_line <= lineno:
689 return template_line
690 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200691
Armin Ronacher9a822052008-04-17 18:44:07 +0200692 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200693 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200694 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200695 if self._uptodate is None:
696 return True
697 return self._uptodate()
698
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200699 @property
700 def debug_info(self):
701 """The debug info mapping."""
702 return [tuple(map(int, x.split('='))) for x in
703 self._debug_info.split('&')]
704
Armin Ronacherc63243e2008-04-14 22:53:58 +0200705 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200706 if self.name is None:
707 name = 'memory:%x' % id(self)
708 else:
709 name = repr(self.name)
710 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200711
712
Armin Ronacherd84ec462008-04-29 13:43:16 +0200713class TemplateModule(object):
714 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200715 template are available as attributes on this object. Additionally
716 converting it into an unicode- or bytestrings renders the contents.
717 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200718
719 def __init__(self, template, context):
Armin Ronacher5411ce72008-05-25 11:36:22 +0200720 self._body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200721 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200722 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200723
Armin Ronacherbbbe0622008-05-19 00:23:37 +0200724 __unicode__ = lambda x: concat(x._body_stream)
Armin Ronacher5411ce72008-05-25 11:36:22 +0200725 __html__ = lambda x: Markup(concat(x._body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200726
727 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200728 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200729
730 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200731 if self.__name__ is None:
732 name = 'memory:%x' % id(self)
733 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200734 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200735 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200736
737
Armin Ronacherba6e25a2008-11-02 15:58:14 +0100738class TemplateExpression(object):
739 """The :meth:`jinja2.Environment.compile_expression` method returns an
740 instance of this object. It encapsulates the expression-like access
741 to the template with an expression it wraps.
742 """
743
744 def __init__(self, template, undefined_to_none):
745 self._template = template
746 self._undefined_to_none = undefined_to_none
747
748 def __call__(self, *args, **kwargs):
749 context = self._template.new_context(dict(*args, **kwargs))
750 consume(self._template.root_render_func(context))
751 rv = context.vars['result']
752 if self._undefined_to_none and isinstance(rv, Undefined):
753 rv = None
754 return rv
755
756
Armin Ronacherc63243e2008-04-14 22:53:58 +0200757class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200758 """A template stream works pretty much like an ordinary python generator
759 but it can buffer multiple items to reduce the number of total iterations.
760 Per default the output is unbuffered which means that for every unbuffered
761 instruction in the template one unicode string is yielded.
762
763 If buffering is enabled with a buffer size of 5, five items are combined
764 into a new unicode string. This is mainly useful if you are streaming
765 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200766 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200767
768 def __init__(self, gen):
769 self._gen = gen
Armin Ronacher9cf95912008-05-24 19:54:43 +0200770 self.disable_buffering()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200771
Armin Ronacher74b51062008-06-17 11:28:59 +0200772 def dump(self, fp, encoding=None, errors='strict'):
773 """Dump the complete stream into a file or file-like object.
774 Per default unicode strings are written, if you want to encode
775 before writing specifiy an `encoding`.
776
777 Example usage::
778
779 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
780 """
781 close = False
782 if isinstance(fp, basestring):
783 fp = file(fp, 'w')
784 close = True
785 try:
786 if encoding is not None:
787 iterable = (x.encode(encoding, errors) for x in self)
788 else:
789 iterable = self
790 if hasattr(fp, 'writelines'):
791 fp.writelines(iterable)
792 else:
793 for item in iterable:
794 fp.write(item)
795 finally:
796 if close:
797 fp.close()
798
Armin Ronacherc63243e2008-04-14 22:53:58 +0200799 def disable_buffering(self):
800 """Disable the output buffering."""
801 self._next = self._gen.next
802 self.buffered = False
803
804 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200805 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200806 if size <= 1:
807 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200808
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200809 def generator(next):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200810 buf = []
811 c_size = 0
812 push = buf.append
Armin Ronacherc63243e2008-04-14 22:53:58 +0200813
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200814 while 1:
815 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200816 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200817 c = next()
818 push(c)
819 if c:
820 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200821 except StopIteration:
822 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200823 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200824 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200825 del buf[:]
826 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200827
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200828 self.buffered = True
Armin Ronacher5dfbfc12008-05-25 18:10:12 +0200829 self._next = generator(self._gen.next).next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200830
831 def __iter__(self):
832 return self
833
834 def next(self):
835 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200836
837
838# hook in default template class. if anyone reads this comment: ignore that
839# it's possible to use custom templates ;-)
840Environment.template_class = Template