blob: 2fbe217b8dd844adc4fea2039e6c7448f899034e [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 Ronacher82b3f3d2008-03-31 20:01:08 +020013from jinja2.lexer import Lexer
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.debug import translate_exception, translate_syntax_error
19from jinja2.exceptions import TemplateSyntaxError
Armin Ronacher7ceced52008-05-03 10:15:31 +020020from jinja2.utils import import_string, LRUCache, Markup, missing, concat
Armin Ronacher07bc6842008-03-31 14:18:49 +020021
22
Armin Ronacher203bfcb2008-04-24 21:54:44 +020023# for direct template usage we have up to ten living environments
24_spontaneous_environments = LRUCache(10)
25
26
Armin Ronacherb5124e62008-04-25 00:36:14 +020027def get_spontaneous_environment(*args):
Armin Ronacher203bfcb2008-04-24 21:54:44 +020028 """Return a new spontaneus environment. A spontaneus environment is an
29 unnamed and unaccessable (in theory) environment that is used for
30 template generated from a string and not from the file system.
31 """
32 try:
33 env = _spontaneous_environments.get(args)
34 except TypeError:
35 return Environment(*args)
36 if env is not None:
37 return env
38 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020039 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020040 return env
41
42
Armin Ronacher7259c762008-04-30 13:03:59 +020043def create_cache(size):
44 """Return the cache class for the given size."""
45 if size == 0:
46 return None
47 if size < 0:
48 return {}
49 return LRUCache(size)
50
51
52def load_extensions(environment, extensions):
53 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020054 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020055 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020056 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020057 for extension in extensions:
58 if isinstance(extension, basestring):
59 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020060 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020061 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020062
Armin Ronacher203bfcb2008-04-24 21:54:44 +020063
Armin Ronacher7259c762008-04-30 13:03:59 +020064def _environment_sanity_check(environment):
65 """Perform a sanity check on the environment."""
66 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
67 'be a subclass of undefined because filters depend on it.'
68 assert environment.block_start_string != \
69 environment.variable_start_string != \
70 environment.comment_start_string, 'block, variable and comment ' \
71 'start strings must be different'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020072 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020073
74
Armin Ronacher07bc6842008-03-31 14:18:49 +020075class Environment(object):
Armin Ronacherd1342312008-04-28 12:20:12 +020076 """The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020077 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020078 globals and others. Instances of this class may be modified if
79 they are not shared and if no template was loaded so far.
80 Modifications on environments after the first template was loaded
81 will lead to surprising effects and undefined behavior.
82
83 Here the possible initialization parameters:
84
Armin Ronacher7b5680c2008-05-06 16:54:22 +020085 `block_start_string`
86 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020087
Armin Ronacher7b5680c2008-05-06 16:54:22 +020088 `block_end_string`
89 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020090
Armin Ronacher7b5680c2008-05-06 16:54:22 +020091 `variable_start_string`
92 The string marking the begin of a print statement.
93 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +020094
Armin Ronacher7b5680c2008-05-06 16:54:22 +020095 `variable_stop_string`
96 The string marking the end of a print statement. Defaults to
97 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020098
Armin Ronacher7b5680c2008-05-06 16:54:22 +020099 `comment_start_string`
100 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200101
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200102 `comment_end_string`
103 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200104
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200105 `line_statement_prefix`
106 If given and a string, this will be used as prefix for line based
107 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200108
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200109 `trim_blocks`
110 If this is set to ``True`` the first newline after a block is
111 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200112
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200113 `extensions`
114 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200115 as strings or extension classes. For more information have a
116 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200117
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200118 `optimized`
119 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200120
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200121 `undefined`
122 :class:`Undefined` or a subclass of it that is used to represent
123 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200124
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200125 `finalize`
126 A callable that finalizes the variable. Per default no finalizing
127 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200128
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200129 `autoescape`
130 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherd1342312008-04-28 12:20:12 +0200131
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200132 `loader`
133 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200134
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200135 `cache_size`
136 The size of the cache. Per default this is ``50`` which means
137 that if more than 50 templates are loaded the loader will clean
138 out the least recently used template. If the cache size is set to
139 ``0`` templates are recompiled all the time, if the cache size is
140 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200141
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200142 `auto_reload`
143 Some loaders load templates from locations where the template
144 sources may change (ie: file system or database). If
145 `auto_reload` is set to `True` (default) every time a template is
146 requested the loader checks if the source changed and if yes, it
147 will reload the template. For higher performance it's possible to
148 disable that.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200149 """
150
Armin Ronacherc63243e2008-04-14 22:53:58 +0200151 #: if this environment is sandboxed. Modifying this variable won't make
152 #: the environment sandboxed though. For a real sandboxed environment
153 #: have a look at jinja2.sandbox
154 sandboxed = False
155
Armin Ronacher7259c762008-04-30 13:03:59 +0200156 #: True if the environment is just an overlay
157 overlay = False
158
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200159 #: the environment this environment is linked to if it is an overlay
160 linked_to = None
161
Armin Ronacherc9705c22008-04-27 21:28:03 +0200162 #: shared environments have this set to `True`. A shared environment
163 #: must not be modified
164 shared = False
165
Armin Ronacher07bc6842008-03-31 14:18:49 +0200166 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200167 block_start_string=BLOCK_START_STRING,
168 block_end_string=BLOCK_END_STRING,
169 variable_start_string=VARIABLE_START_STRING,
170 variable_end_string=VARIABLE_END_STRING,
171 comment_start_string=COMMENT_START_STRING,
172 comment_end_string=COMMENT_END_STRING,
173 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher07bc6842008-03-31 14:18:49 +0200174 trim_blocks=False,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200175 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200176 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200177 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200178 finalize=None,
179 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200180 loader=None,
181 cache_size=50,
182 auto_reload=True):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200183 # !!Important notice!!
184 # The constructor accepts quite a few arguments that should be
185 # passed by keyword rather than position. However it's important to
186 # not change the order of arguments because it's used at least
187 # internally in those cases:
188 # - spontaneus environments (i18n extension and Template)
189 # - unittests
190 # If parameter changes are required only add parameters at the end
191 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200192 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200193
194 # lexer / parser information
195 self.block_start_string = block_start_string
196 self.block_end_string = block_end_string
197 self.variable_start_string = variable_start_string
198 self.variable_end_string = variable_end_string
199 self.comment_start_string = comment_start_string
200 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200201 self.line_statement_prefix = line_statement_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200202 self.trim_blocks = trim_blocks
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200203
Armin Ronacherf59bac22008-04-20 13:11:43 +0200204 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200205 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200206 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200207 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200208 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200209
210 # defaults
211 self.filters = DEFAULT_FILTERS.copy()
212 self.tests = DEFAULT_TESTS.copy()
213 self.globals = DEFAULT_NAMESPACE.copy()
214
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200215 # set the loader provided
216 self.loader = loader
Armin Ronacher7259c762008-04-30 13:03:59 +0200217 self.cache = create_cache(cache_size)
218 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200219
Armin Ronacherb5124e62008-04-25 00:36:14 +0200220 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200221 self.extensions = load_extensions(self, extensions)
222
223 _environment_sanity_check(self)
224
Armin Ronacher762079c2008-05-08 23:57:56 +0200225 def extend(self, **attributes):
226 """Add the items to the instance of the environment if they do not exist
227 yet. This is used by :ref:`extensions <writing-extensions>` to register
228 callbacks and configuration values without breaking inheritance.
229 """
230 for key, value in attributes.iteritems():
231 if not hasattr(self, key):
232 setattr(self, key, value)
233
Armin Ronacher7259c762008-04-30 13:03:59 +0200234 def overlay(self, block_start_string=missing, block_end_string=missing,
235 variable_start_string=missing, variable_end_string=missing,
236 comment_start_string=missing, comment_end_string=missing,
237 line_statement_prefix=missing, trim_blocks=missing,
238 extensions=missing, optimized=missing, undefined=missing,
239 finalize=missing, autoescape=missing, loader=missing,
240 cache_size=missing, auto_reload=missing):
241 """Create a new overlay environment that shares all the data with the
242 current environment except of cache and the overriden attributes.
243 Extensions cannot be removed for a overlayed environment. A overlayed
244 environment automatically gets all the extensions of the environment it
245 is linked to plus optional extra extensions.
246
247 Creating overlays should happen after the initial environment was set
248 up completely. Not all attributes are truly linked, some are just
249 copied over so modifications on the original environment may not shine
250 through.
251 """
252 args = dict(locals())
253 del args['self'], args['cache_size'], args['extensions']
254
255 rv = object.__new__(self.__class__)
256 rv.__dict__.update(self.__dict__)
257 rv.overlay = True
258 rv.linked_to = self
259
260 for key, value in args.iteritems():
261 if value is not missing:
262 setattr(rv, key, value)
263
264 if cache_size is not missing:
265 rv.cache = create_cache(cache_size)
266
Armin Ronacher023b5e92008-05-08 11:03:10 +0200267 rv.extensions = {}
268 for key, value in self.extensions.iteritems():
269 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200270 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200271 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200272
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200273 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200274
275 @property
276 def lexer(self):
277 """Return a fresh lexer for the environment."""
278 return Lexer(self)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200279
Armin Ronacherc63243e2008-04-14 22:53:58 +0200280 def subscribe(self, obj, argument):
281 """Get an item or attribute of an object."""
282 try:
283 return getattr(obj, str(argument))
284 except (AttributeError, UnicodeError):
285 try:
286 return obj[argument]
287 except (TypeError, LookupError):
Armin Ronacher9a822052008-04-17 18:44:07 +0200288 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200289
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200290 def parse(self, source, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200291 """Parse the sourcecode and return the abstract syntax tree. This
292 tree of nodes is used by the compiler to convert the template into
293 executable source- or bytecode. This is useful for debugging or to
294 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200295
296 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
297 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200298 """
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200299 try:
300 return Parser(self, source, filename).parse()
301 except TemplateSyntaxError, e:
302 exc_type, exc_value, tb = translate_syntax_error(e)
303 raise exc_type, exc_value, tb
Armin Ronacher07bc6842008-03-31 14:18:49 +0200304
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200305 def lex(self, source, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200306 """Lex the given sourcecode and return a generator that yields
307 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200308 This can be useful for :ref:`extension development <writing-extensions>`
309 and debugging templates.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200310 """
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200311 return self.lexer.tokeniter(source, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200312
Armin Ronacher814f6c22008-04-17 15:52:23 +0200313 def compile(self, source, name=None, filename=None, globals=None,
314 raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200315 """Compile a node or template source code. The `name` parameter is
316 the load name of the template after it was joined using
317 :meth:`join_path` if necessary, not the filename on the file system.
318 the `filename` parameter is the estimated filename of the template on
319 the file system. If the template came from a database or memory this
320 can be omitted. The `globals` parameter can be used to provide extra
321 variables at compile time for the template. In the future the
322 optimizer will be able to evaluate parts of the template at compile
323 time based on those variables.
324
325 The return value of this method is a python code object. If the `raw`
326 parameter is `True` the return value will be a string with python
327 code equivalent to the bytecode returned otherwise. This method is
328 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200329 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200330 if isinstance(source, basestring):
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200331 source = self.parse(source, filename)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200332 if self.optimized:
333 node = optimize(source, self, globals or {})
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200334 source = generate(node, self, name, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200335 if raw:
336 return source
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200337 if filename is None:
Armin Ronacher68f77672008-04-17 11:50:39 +0200338 filename = '<template>'
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200339 elif isinstance(filename, unicode):
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200340 filename = filename.encode('utf-8')
341 return compile(source, filename, 'exec')
342
343 def join_path(self, template, parent):
344 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200345 relative to the loader root so this method returns the `template`
346 parameter unchanged, but if the paths should be relative to the
347 parent template, this function can be used to calculate the real
348 template name.
349
350 Subclasses may override this method and implement template path
351 joining here.
352 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200353 return template
354
Armin Ronacherfed44b52008-04-13 19:42:53 +0200355 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200356 """Load a template from the loader. If a loader is configured this
357 method ask the loader for the template and returns a :class:`Template`.
358 If the `parent` parameter is not `None`, :meth:`join_path` is called
359 to get the real template name before loading.
360
361 The `globals` parameter can be used to provide compile-time globals.
362 In the future this will allow the optimizer to render parts of the
363 templates at compile-time.
364
365 If the template does not exist a :exc:`TemplateNotFound` exception is
366 raised.
367 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200368 if self.loader is None:
369 raise TypeError('no loader for this environment specified')
370 if parent is not None:
371 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200372
373 if self.cache is not None:
374 template = self.cache.get(name)
375 if template is not None and (not self.auto_reload or \
376 template.is_up_to_date):
377 return template
378
379 template = self.loader.load(self, name, self.make_globals(globals))
380 if self.cache is not None:
381 self.cache[name] = template
382 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200383
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200384 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200385 """Load a template from a string. This parses the source given and
386 returns a :class:`Template` object.
387 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200388 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200389 cls = template_class or self.template_class
390 return cls.from_code(self, self.compile(source, globals=globals),
391 globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200392
393 def make_globals(self, d):
394 """Return a dict for the globals."""
395 if d is None:
396 return self.globals
397 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200398
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200399
400class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200401 """The central template object. This class represents a compiled template
402 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200403
Armin Ronacherd1342312008-04-28 12:20:12 +0200404 Normally the template object is generated from an :class:`Environment` but
405 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200406 instance directly using the constructor. It takes the same arguments as
407 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200408
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200409 Every template object has a few methods and members that are guaranteed
410 to exist. However it's important that a template object should be
411 considered immutable. Modifications on the object are not supported.
412
413 Template objects created from the constructor rather than an environment
414 do have an `environment` attribute that points to a temporary environment
415 that is probably shared with other templates created with the constructor
416 and compatible settings.
417
418 >>> template = Template('Hello {{ name }}!')
419 >>> template.render(name='John Doe')
420 u'Hello John Doe!'
421
422 >>> stream = template.stream(name='John Doe')
423 >>> stream.next()
424 u'Hello John Doe!'
425 >>> stream.next()
426 Traceback (most recent call last):
427 ...
428 StopIteration
429 """
430
431 def __new__(cls, source,
432 block_start_string='{%',
433 block_end_string='%}',
434 variable_start_string='{{',
435 variable_end_string='}}',
436 comment_start_string='{#',
437 comment_end_string='#}',
438 line_statement_prefix=None,
439 trim_blocks=False,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200440 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200441 optimized=True,
442 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200443 finalize=None,
444 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200445 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200446 block_start_string, block_end_string, variable_start_string,
447 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200448 line_statement_prefix, trim_blocks, tuple(extensions), optimized,
Armin Ronacher7259c762008-04-30 13:03:59 +0200449 undefined, finalize, autoescape, None, 0, False)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200450 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200451
Armin Ronacher7259c762008-04-30 13:03:59 +0200452 @classmethod
453 def from_code(cls, environment, code, globals, uptodate=None):
454 """Creates a template object from compiled code and the globals. This
455 is used by the loaders and environment to create a template object.
456 """
457 t = object.__new__(cls)
458 namespace = {
459 'environment': environment,
460 '__jinja_template__': t
461 }
462 exec code in namespace
463 t.environment = environment
464 t.name = namespace['name']
465 t.filename = code.co_filename
466 t.root_render_func = namespace['root']
467 t.blocks = namespace['blocks']
468 t.globals = globals
469
470 # debug and loader helpers
471 t._debug_info = namespace['debug_info']
472 t._uptodate = uptodate
473
474 return t
475
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200476 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200477 """This method accepts the same arguments as the `dict` constructor:
478 A dict, a dict subclass or some keyword arguments. If no arguments
479 are given the context will be empty. These two calls do the same::
480
481 template.render(knights='that say nih')
482 template.render({'knights': 'that say nih'})
483
484 This will return the rendered template as unicode string.
485 """
Armin Ronacherf41d1392008-04-18 16:41:52 +0200486 try:
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200487 return concat(self._generate(*args, **kwargs))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200488 except:
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200489 exc_type, exc_value, tb = translate_exception(sys.exc_info())
490 raise exc_type, exc_value, tb
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200491
492 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200493 """Works exactly like :meth:`generate` but returns a
494 :class:`TemplateStream`.
495 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200496 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200497
498 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200499 """For very large templates it can be useful to not render the whole
500 template at once but evaluate each statement after another and yield
501 piece for piece. This method basically does exactly that and returns
502 a generator that yields one item after another as unicode strings.
503
504 It accepts the same arguments as :meth:`render`.
505 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200506 try:
507 for item in self._generate(*args, **kwargs):
508 yield item
509 except:
510 exc_type, exc_value, tb = translate_exception(sys.exc_info())
511 raise exc_type, exc_value, tb
512
513 def _generate(self, *args, **kwargs):
Armin Ronacherfed44b52008-04-13 19:42:53 +0200514 # assemble the context
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200515 context = dict(*args, **kwargs)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200516
517 # if the environment is using the optimizer locals may never
518 # override globals as optimizations might have happened
519 # depending on values of certain globals. This assertion goes
520 # away if the python interpreter is started with -O
521 if __debug__ and self.environment.optimized:
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200522 overrides = set(context) & set(self.globals)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200523 if overrides:
524 plural = len(overrides) != 1 and 's' or ''
525 raise AssertionError('the per template variable%s %s '
526 'override%s global variable%s. '
527 'With an enabled optimizer this '
528 'will lead to unexpected results.' %
529 (plural, ', '.join(overrides), plural or ' a', plural))
Armin Ronacherba3757b2008-04-16 19:43:16 +0200530
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200531 return self.root_render_func(self.new_context(context))
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200532
Armin Ronacherc9705c22008-04-27 21:28:03 +0200533 def new_context(self, vars=None, shared=False):
534 """Create a new template context for this template. The vars
535 provided will be passed to the template. Per default the globals
536 are added to the context, if shared is set to `True` the data
537 provided is used as parent namespace. This is used to share the
538 same globals in multiple contexts without consuming more memory.
539 (This works because the context does not modify the parent dict)
540 """
541 if vars is None:
542 vars = {}
543 if shared:
544 parent = vars
545 else:
546 parent = dict(self.globals, **vars)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200547 return Context(self.environment, parent, self.name, self.blocks)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200548
Armin Ronacherea847c52008-05-02 20:04:32 +0200549 def make_module(self, vars=None, shared=False):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200550 """This method works like the :attr:`module` attribute when called
551 without arguments but it will evaluate the template every call
552 rather then caching the template. It's also possible to provide
553 a dict which is then used as context. The arguments are the same
554 as fo the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200555 """
556 return TemplateModule(self, self.new_context(vars, shared))
557
Armin Ronacherd84ec462008-04-29 13:43:16 +0200558 @property
559 def module(self):
560 """The template as module. This is used for imports in the
561 template runtime but is also useful if one wants to access
562 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200563
Armin Ronacherd84ec462008-04-29 13:43:16 +0200564 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
565 >>> unicode(t.module)
566 u'23'
567 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200568 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200569 """
Armin Ronacherd84ec462008-04-29 13:43:16 +0200570 if hasattr(self, '_module'):
571 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200572 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200573 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200574
Armin Ronacherba3757b2008-04-16 19:43:16 +0200575 def get_corresponding_lineno(self, lineno):
576 """Return the source line number of a line number in the
577 generated bytecode as they are not in sync.
578 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200579 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200580 if code_line <= lineno:
581 return template_line
582 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200583
Armin Ronacher9a822052008-04-17 18:44:07 +0200584 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200585 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200586 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200587 if self._uptodate is None:
588 return True
589 return self._uptodate()
590
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200591 @property
592 def debug_info(self):
593 """The debug info mapping."""
594 return [tuple(map(int, x.split('='))) for x in
595 self._debug_info.split('&')]
596
Armin Ronacherc63243e2008-04-14 22:53:58 +0200597 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200598 if self.name is None:
599 name = 'memory:%x' % id(self)
600 else:
601 name = repr(self.name)
602 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200603
604
Armin Ronacherd84ec462008-04-29 13:43:16 +0200605class TemplateModule(object):
606 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200607 template are available as attributes on this object. Additionally
608 converting it into an unicode- or bytestrings renders the contents.
609 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200610
611 def __init__(self, template, context):
Armin Ronacherea847c52008-05-02 20:04:32 +0200612 # don't alter this attribute unless you change it in the
613 # compiler too. The Include without context passing directly
614 # uses the mangled name. The reason why we use a mangled one
615 # is to avoid name clashes with macros with those names.
Armin Ronacher7ceced52008-05-03 10:15:31 +0200616 self.__body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200617 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200618 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200619
Armin Ronacher53042292008-04-26 18:30:19 +0200620 __html__ = lambda x: Markup(concat(x.__body_stream))
621 __unicode__ = lambda x: unicode(concat(x.__body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200622
623 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200624 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200625
626 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200627 if self.__name__ is None:
628 name = 'memory:%x' % id(self)
629 else:
630 name = repr(self.name)
631 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200632
633
Armin Ronacherc63243e2008-04-14 22:53:58 +0200634class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200635 """A template stream works pretty much like an ordinary python generator
636 but it can buffer multiple items to reduce the number of total iterations.
637 Per default the output is unbuffered which means that for every unbuffered
638 instruction in the template one unicode string is yielded.
639
640 If buffering is enabled with a buffer size of 5, five items are combined
641 into a new unicode string. This is mainly useful if you are streaming
642 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200643 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200644
645 def __init__(self, gen):
646 self._gen = gen
647 self._next = gen.next
648 self.buffered = False
649
650 def disable_buffering(self):
651 """Disable the output buffering."""
652 self._next = self._gen.next
653 self.buffered = False
654
655 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200656 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200657 if size <= 1:
658 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200659
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200660 def generator():
Armin Ronacherc63243e2008-04-14 22:53:58 +0200661 buf = []
662 c_size = 0
663 push = buf.append
664 next = self._gen.next
665
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200666 while 1:
667 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200668 while c_size < size:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200669 push(next())
Armin Ronacherc63243e2008-04-14 22:53:58 +0200670 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200671 except StopIteration:
672 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200673 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200674 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200675 del buf[:]
676 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200677
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200678 self.buffered = True
679 self._next = generator().next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200680
681 def __iter__(self):
682 return self
683
684 def next(self):
685 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200686
687
688# hook in default template class. if anyone reads this comment: ignore that
689# it's possible to use custom templates ;-)
690Environment.template_class = Template