blob: f64b150f543ad8a79796bfa963cbd6261ac7a69b [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.exceptions import TemplateSyntaxError
Armin Ronacher7ceced52008-05-03 10:15:31 +020019from jinja2.utils import import_string, LRUCache, Markup, missing, concat
Armin Ronacher07bc6842008-03-31 14:18:49 +020020
21
Armin Ronacher203bfcb2008-04-24 21:54:44 +020022# for direct template usage we have up to ten living environments
23_spontaneous_environments = LRUCache(10)
24
25
Armin Ronacherb5124e62008-04-25 00:36:14 +020026def get_spontaneous_environment(*args):
Armin Ronacher203bfcb2008-04-24 21:54:44 +020027 """Return a new spontaneus environment. A spontaneus environment is an
28 unnamed and unaccessable (in theory) environment that is used for
29 template generated from a string and not from the file system.
30 """
31 try:
32 env = _spontaneous_environments.get(args)
33 except TypeError:
34 return Environment(*args)
35 if env is not None:
36 return env
37 _spontaneous_environments[args] = env = Environment(*args)
Armin Ronacherc9705c22008-04-27 21:28:03 +020038 env.shared = True
Armin Ronacher203bfcb2008-04-24 21:54:44 +020039 return env
40
41
Armin Ronacher7259c762008-04-30 13:03:59 +020042def create_cache(size):
43 """Return the cache class for the given size."""
44 if size == 0:
45 return None
46 if size < 0:
47 return {}
48 return LRUCache(size)
49
50
51def load_extensions(environment, extensions):
52 """Load the extensions from the list and bind it to the environment.
Armin Ronacher023b5e92008-05-08 11:03:10 +020053 Returns a dict of instanciated environments.
Armin Ronacher203bfcb2008-04-24 21:54:44 +020054 """
Armin Ronacher023b5e92008-05-08 11:03:10 +020055 result = {}
Armin Ronacher7259c762008-04-30 13:03:59 +020056 for extension in extensions:
57 if isinstance(extension, basestring):
58 extension = import_string(extension)
Armin Ronacher023b5e92008-05-08 11:03:10 +020059 result[extension.identifier] = extension(environment)
Armin Ronacher7259c762008-04-30 13:03:59 +020060 return result
Armin Ronacher203bfcb2008-04-24 21:54:44 +020061
Armin Ronacher203bfcb2008-04-24 21:54:44 +020062
Armin Ronacher7259c762008-04-30 13:03:59 +020063def _environment_sanity_check(environment):
64 """Perform a sanity check on the environment."""
65 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
66 'be a subclass of undefined because filters depend on it.'
67 assert environment.block_start_string != \
68 environment.variable_start_string != \
69 environment.comment_start_string, 'block, variable and comment ' \
70 'start strings must be different'
Armin Ronacher19cf9c22008-05-01 12:49:53 +020071 return environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020072
73
Armin Ronacher07bc6842008-03-31 14:18:49 +020074class Environment(object):
Armin Ronacherd1342312008-04-28 12:20:12 +020075 """The core component of Jinja is the `Environment`. It contains
Armin Ronacher07bc6842008-03-31 14:18:49 +020076 important shared variables like configuration, filters, tests,
Armin Ronacherd1342312008-04-28 12:20:12 +020077 globals and others. Instances of this class may be modified if
78 they are not shared and if no template was loaded so far.
79 Modifications on environments after the first template was loaded
80 will lead to surprising effects and undefined behavior.
81
82 Here the possible initialization parameters:
83
Armin Ronacher7b5680c2008-05-06 16:54:22 +020084 `block_start_string`
85 The string marking the begin of a block. Defaults to ``'{%'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020086
Armin Ronacher7b5680c2008-05-06 16:54:22 +020087 `block_end_string`
88 The string marking the end of a block. Defaults to ``'%}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020089
Armin Ronacher7b5680c2008-05-06 16:54:22 +020090 `variable_start_string`
91 The string marking the begin of a print statement.
92 Defaults to ``'{{'``.
Armin Ronacher115de2e2008-05-01 22:20:05 +020093
Armin Ronacher7b5680c2008-05-06 16:54:22 +020094 `variable_stop_string`
95 The string marking the end of a print statement. Defaults to
96 ``'}}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +020097
Armin Ronacher7b5680c2008-05-06 16:54:22 +020098 `comment_start_string`
99 The string marking the begin of a comment. Defaults to ``'{#'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200100
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200101 `comment_end_string`
102 The string marking the end of a comment. Defaults to ``'#}'``.
Armin Ronacherd1342312008-04-28 12:20:12 +0200103
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200104 `line_statement_prefix`
105 If given and a string, this will be used as prefix for line based
106 statements. See also :ref:`line-statements`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200107
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200108 `trim_blocks`
109 If this is set to ``True`` the first newline after a block is
110 removed (block, not variable tag!). Defaults to `False`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200111
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200112 `extensions`
113 List of Jinja extensions to use. This can either be import paths
Armin Ronachered98cac2008-05-07 08:42:11 +0200114 as strings or extension classes. For more information have a
115 look at :ref:`the extensions documentation <jinja-extensions>`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200116
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200117 `optimized`
118 should the optimizer be enabled? Default is `True`.
Armin Ronacherd1342312008-04-28 12:20:12 +0200119
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200120 `undefined`
121 :class:`Undefined` or a subclass of it that is used to represent
122 undefined values in the template.
Armin Ronacherd1342312008-04-28 12:20:12 +0200123
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200124 `finalize`
125 A callable that finalizes the variable. Per default no finalizing
126 is applied.
Armin Ronacherd1342312008-04-28 12:20:12 +0200127
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200128 `autoescape`
129 If set to true the XML/HTML autoescaping feature is enabled.
Armin Ronacherd1342312008-04-28 12:20:12 +0200130
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200131 `loader`
132 The template loader for this environment.
Armin Ronacher7259c762008-04-30 13:03:59 +0200133
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200134 `cache_size`
135 The size of the cache. Per default this is ``50`` which means
136 that if more than 50 templates are loaded the loader will clean
137 out the least recently used template. If the cache size is set to
138 ``0`` templates are recompiled all the time, if the cache size is
139 ``-1`` the cache will not be cleaned.
Armin Ronacher7259c762008-04-30 13:03:59 +0200140
Armin Ronacher7b5680c2008-05-06 16:54:22 +0200141 `auto_reload`
142 Some loaders load templates from locations where the template
143 sources may change (ie: file system or database). If
144 `auto_reload` is set to `True` (default) every time a template is
145 requested the loader checks if the source changed and if yes, it
146 will reload the template. For higher performance it's possible to
147 disable that.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200148 """
149
Armin Ronacherc63243e2008-04-14 22:53:58 +0200150 #: if this environment is sandboxed. Modifying this variable won't make
151 #: the environment sandboxed though. For a real sandboxed environment
152 #: have a look at jinja2.sandbox
153 sandboxed = False
154
Armin Ronacher7259c762008-04-30 13:03:59 +0200155 #: True if the environment is just an overlay
156 overlay = False
157
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200158 #: the environment this environment is linked to if it is an overlay
159 linked_to = None
160
Armin Ronacherc9705c22008-04-27 21:28:03 +0200161 #: shared environments have this set to `True`. A shared environment
162 #: must not be modified
163 shared = False
164
Armin Ronacher07bc6842008-03-31 14:18:49 +0200165 def __init__(self,
Armin Ronacher7259c762008-04-30 13:03:59 +0200166 block_start_string=BLOCK_START_STRING,
167 block_end_string=BLOCK_END_STRING,
168 variable_start_string=VARIABLE_START_STRING,
169 variable_end_string=VARIABLE_END_STRING,
170 comment_start_string=COMMENT_START_STRING,
171 comment_end_string=COMMENT_END_STRING,
172 line_statement_prefix=LINE_STATEMENT_PREFIX,
Armin Ronacher07bc6842008-03-31 14:18:49 +0200173 trim_blocks=False,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200174 extensions=(),
Armin Ronacherfed44b52008-04-13 19:42:53 +0200175 optimized=True,
Armin Ronacherc63243e2008-04-14 22:53:58 +0200176 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200177 finalize=None,
178 autoescape=False,
Armin Ronacher7259c762008-04-30 13:03:59 +0200179 loader=None,
180 cache_size=50,
181 auto_reload=True):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200182 # !!Important notice!!
183 # The constructor accepts quite a few arguments that should be
184 # passed by keyword rather than position. However it's important to
185 # not change the order of arguments because it's used at least
186 # internally in those cases:
187 # - spontaneus environments (i18n extension and Template)
188 # - unittests
189 # If parameter changes are required only add parameters at the end
190 # and don't change the arguments (or the defaults!) of the arguments
Armin Ronacher7259c762008-04-30 13:03:59 +0200191 # existing already.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200192
193 # lexer / parser information
194 self.block_start_string = block_start_string
195 self.block_end_string = block_end_string
196 self.variable_start_string = variable_start_string
197 self.variable_end_string = variable_end_string
198 self.comment_start_string = comment_start_string
199 self.comment_end_string = comment_end_string
Armin Ronacherbf7c4ad2008-04-12 12:02:36 +0200200 self.line_statement_prefix = line_statement_prefix
Armin Ronacher07bc6842008-03-31 14:18:49 +0200201 self.trim_blocks = trim_blocks
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200202
Armin Ronacherf59bac22008-04-20 13:11:43 +0200203 # runtime information
Armin Ronacherc63243e2008-04-14 22:53:58 +0200204 self.undefined = undefined
Armin Ronacherfed44b52008-04-13 19:42:53 +0200205 self.optimized = optimized
Armin Ronacher18c6ca02008-04-17 10:03:29 +0200206 self.finalize = finalize
Armin Ronacherd1342312008-04-28 12:20:12 +0200207 self.autoescape = autoescape
Armin Ronacher07bc6842008-03-31 14:18:49 +0200208
209 # defaults
210 self.filters = DEFAULT_FILTERS.copy()
211 self.tests = DEFAULT_TESTS.copy()
212 self.globals = DEFAULT_NAMESPACE.copy()
213
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200214 # set the loader provided
215 self.loader = loader
Armin Ronacher7259c762008-04-30 13:03:59 +0200216 self.cache = create_cache(cache_size)
217 self.auto_reload = auto_reload
Armin Ronacher07bc6842008-03-31 14:18:49 +0200218
Armin Ronacherb5124e62008-04-25 00:36:14 +0200219 # load extensions
Armin Ronacher7259c762008-04-30 13:03:59 +0200220 self.extensions = load_extensions(self, extensions)
221
222 _environment_sanity_check(self)
223
Armin Ronacher762079c2008-05-08 23:57:56 +0200224 def extend(self, **attributes):
225 """Add the items to the instance of the environment if they do not exist
226 yet. This is used by :ref:`extensions <writing-extensions>` to register
227 callbacks and configuration values without breaking inheritance.
228 """
229 for key, value in attributes.iteritems():
230 if not hasattr(self, key):
231 setattr(self, key, value)
232
Armin Ronacher7259c762008-04-30 13:03:59 +0200233 def overlay(self, block_start_string=missing, block_end_string=missing,
234 variable_start_string=missing, variable_end_string=missing,
235 comment_start_string=missing, comment_end_string=missing,
236 line_statement_prefix=missing, trim_blocks=missing,
237 extensions=missing, optimized=missing, undefined=missing,
238 finalize=missing, autoescape=missing, loader=missing,
239 cache_size=missing, auto_reload=missing):
240 """Create a new overlay environment that shares all the data with the
241 current environment except of cache and the overriden attributes.
242 Extensions cannot be removed for a overlayed environment. A overlayed
243 environment automatically gets all the extensions of the environment it
244 is linked to plus optional extra extensions.
245
246 Creating overlays should happen after the initial environment was set
247 up completely. Not all attributes are truly linked, some are just
248 copied over so modifications on the original environment may not shine
249 through.
250 """
251 args = dict(locals())
252 del args['self'], args['cache_size'], args['extensions']
253
254 rv = object.__new__(self.__class__)
255 rv.__dict__.update(self.__dict__)
256 rv.overlay = True
257 rv.linked_to = self
258
259 for key, value in args.iteritems():
260 if value is not missing:
261 setattr(rv, key, value)
262
263 if cache_size is not missing:
264 rv.cache = create_cache(cache_size)
265
Armin Ronacher023b5e92008-05-08 11:03:10 +0200266 rv.extensions = {}
267 for key, value in self.extensions.iteritems():
268 rv.extensions[key] = value.bind(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200269 if extensions is not missing:
Armin Ronacher023b5e92008-05-08 11:03:10 +0200270 rv.extensions.update(load_extensions(extensions))
Armin Ronacher7259c762008-04-30 13:03:59 +0200271
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200272 return _environment_sanity_check(rv)
Armin Ronacher7259c762008-04-30 13:03:59 +0200273
274 @property
275 def lexer(self):
276 """Return a fresh lexer for the environment."""
277 return Lexer(self)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200278
Armin Ronacherc63243e2008-04-14 22:53:58 +0200279 def subscribe(self, obj, argument):
280 """Get an item or attribute of an object."""
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200281 if isinstance(argument, basestring):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200282 try:
Armin Ronacher08a6a3b2008-05-13 15:35:47 +0200283 return getattr(obj, str(argument))
284 except (AttributeError, UnicodeError):
285 pass
286 try:
287 return obj[argument]
288 except (TypeError, LookupError):
289 return self.undefined(obj=obj, name=argument)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200290
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200291 def parse(self, source, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200292 """Parse the sourcecode and return the abstract syntax tree. This
293 tree of nodes is used by the compiler to convert the template into
294 executable source- or bytecode. This is useful for debugging or to
295 extract information from templates.
Armin Ronachered98cac2008-05-07 08:42:11 +0200296
297 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
298 this gives you a good overview of the node tree generated.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200299 """
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200300 try:
301 return Parser(self, source, filename).parse()
302 except TemplateSyntaxError, e:
Armin Ronacher27069d72008-05-11 19:48:12 +0200303 from jinja2.debug import translate_syntax_error
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200304 exc_type, exc_value, tb = translate_syntax_error(e)
305 raise exc_type, exc_value, tb
Armin Ronacher07bc6842008-03-31 14:18:49 +0200306
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200307 def lex(self, source, filename=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200308 """Lex the given sourcecode and return a generator that yields
309 tokens as tuples in the form ``(lineno, token_type, value)``.
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200310 This can be useful for :ref:`extension development <writing-extensions>`
311 and debugging templates.
Armin Ronacher07bc6842008-03-31 14:18:49 +0200312 """
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200313 return self.lexer.tokeniter(source, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200314
Armin Ronacher981cbf62008-05-13 09:12:27 +0200315 def compile(self, source, name=None, filename=None, raw=False):
Armin Ronacherd1342312008-04-28 12:20:12 +0200316 """Compile a node or template source code. The `name` parameter is
317 the load name of the template after it was joined using
318 :meth:`join_path` if necessary, not the filename on the file system.
319 the `filename` parameter is the estimated filename of the template on
320 the file system. If the template came from a database or memory this
Armin Ronacher981cbf62008-05-13 09:12:27 +0200321 can be omitted.
Armin Ronacherd1342312008-04-28 12:20:12 +0200322
323 The return value of this method is a python code object. If the `raw`
324 parameter is `True` the return value will be a string with python
325 code equivalent to the bytecode returned otherwise. This method is
326 mainly used internally.
Armin Ronacher68f77672008-04-17 11:50:39 +0200327 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200328 if isinstance(source, basestring):
Armin Ronacheraaf010d2008-05-01 13:14:30 +0200329 source = self.parse(source, filename)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200330 if self.optimized:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200331 node = optimize(source, self)
Armin Ronacher8e8d0712008-04-16 23:10:49 +0200332 source = generate(node, self, name, filename)
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200333 if raw:
334 return source
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200335 if filename is None:
Armin Ronacher68f77672008-04-17 11:50:39 +0200336 filename = '<template>'
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200337 elif isinstance(filename, unicode):
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200338 filename = filename.encode('utf-8')
339 return compile(source, filename, 'exec')
340
341 def join_path(self, template, parent):
342 """Join a template with the parent. By default all the lookups are
Armin Ronacherd1342312008-04-28 12:20:12 +0200343 relative to the loader root so this method returns the `template`
344 parameter unchanged, but if the paths should be relative to the
345 parent template, this function can be used to calculate the real
346 template name.
347
348 Subclasses may override this method and implement template path
349 joining here.
350 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200351 return template
352
Armin Ronacherfed44b52008-04-13 19:42:53 +0200353 def get_template(self, name, parent=None, globals=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200354 """Load a template from the loader. If a loader is configured this
355 method ask the loader for the template and returns a :class:`Template`.
356 If the `parent` parameter is not `None`, :meth:`join_path` is called
357 to get the real template name before loading.
358
Armin Ronacher981cbf62008-05-13 09:12:27 +0200359 The `globals` parameter can be used to provide temlate wide globals.
360 These variables are available in the context at render time.
Armin Ronacherd1342312008-04-28 12:20:12 +0200361
362 If the template does not exist a :exc:`TemplateNotFound` exception is
363 raised.
364 """
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200365 if self.loader is None:
366 raise TypeError('no loader for this environment specified')
367 if parent is not None:
368 name = self.join_path(name, parent)
Armin Ronacher7259c762008-04-30 13:03:59 +0200369
370 if self.cache is not None:
371 template = self.cache.get(name)
372 if template is not None and (not self.auto_reload or \
373 template.is_up_to_date):
374 return template
375
376 template = self.loader.load(self, name, self.make_globals(globals))
377 if self.cache is not None:
378 self.cache[name] = template
379 return template
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200380
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200381 def from_string(self, source, globals=None, template_class=None):
Armin Ronacherd1342312008-04-28 12:20:12 +0200382 """Load a template from a string. This parses the source given and
383 returns a :class:`Template` object.
384 """
Armin Ronacherfed44b52008-04-13 19:42:53 +0200385 globals = self.make_globals(globals)
Armin Ronacher7259c762008-04-30 13:03:59 +0200386 cls = template_class or self.template_class
Armin Ronacher981cbf62008-05-13 09:12:27 +0200387 return cls.from_code(self, self.compile(source), globals, None)
Armin Ronacherfed44b52008-04-13 19:42:53 +0200388
389 def make_globals(self, d):
390 """Return a dict for the globals."""
391 if d is None:
392 return self.globals
393 return dict(self.globals, **d)
Armin Ronacher46f5f982008-04-11 16:40:09 +0200394
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200395
396class Template(object):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200397 """The central template object. This class represents a compiled template
398 and is used to evaluate it.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200399
Armin Ronacherd1342312008-04-28 12:20:12 +0200400 Normally the template object is generated from an :class:`Environment` but
401 it also has a constructor that makes it possible to create a template
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200402 instance directly using the constructor. It takes the same arguments as
403 the environment constructor but it's not possible to specify a loader.
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200404
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200405 Every template object has a few methods and members that are guaranteed
406 to exist. However it's important that a template object should be
407 considered immutable. Modifications on the object are not supported.
408
409 Template objects created from the constructor rather than an environment
410 do have an `environment` attribute that points to a temporary environment
411 that is probably shared with other templates created with the constructor
412 and compatible settings.
413
414 >>> template = Template('Hello {{ name }}!')
415 >>> template.render(name='John Doe')
416 u'Hello John Doe!'
417
418 >>> stream = template.stream(name='John Doe')
419 >>> stream.next()
420 u'Hello John Doe!'
421 >>> stream.next()
422 Traceback (most recent call last):
423 ...
424 StopIteration
425 """
426
427 def __new__(cls, source,
428 block_start_string='{%',
429 block_end_string='%}',
430 variable_start_string='{{',
431 variable_end_string='}}',
432 comment_start_string='{#',
433 comment_end_string='#}',
434 line_statement_prefix=None,
435 trim_blocks=False,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200436 extensions=(),
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200437 optimized=True,
438 undefined=Undefined,
Armin Ronacherd1342312008-04-28 12:20:12 +0200439 finalize=None,
440 autoescape=False):
Armin Ronacherb5124e62008-04-25 00:36:14 +0200441 env = get_spontaneous_environment(
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200442 block_start_string, block_end_string, variable_start_string,
443 variable_end_string, comment_start_string, comment_end_string,
Armin Ronacherb5124e62008-04-25 00:36:14 +0200444 line_statement_prefix, trim_blocks, tuple(extensions), optimized,
Armin Ronacher7259c762008-04-30 13:03:59 +0200445 undefined, finalize, autoescape, None, 0, False)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200446 return env.from_string(source, template_class=cls)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200447
Armin Ronacher7259c762008-04-30 13:03:59 +0200448 @classmethod
449 def from_code(cls, environment, code, globals, uptodate=None):
450 """Creates a template object from compiled code and the globals. This
451 is used by the loaders and environment to create a template object.
452 """
453 t = object.__new__(cls)
454 namespace = {
455 'environment': environment,
456 '__jinja_template__': t
457 }
458 exec code in namespace
459 t.environment = environment
460 t.name = namespace['name']
461 t.filename = code.co_filename
462 t.root_render_func = namespace['root']
463 t.blocks = namespace['blocks']
464 t.globals = globals
465
466 # debug and loader helpers
467 t._debug_info = namespace['debug_info']
468 t._uptodate = uptodate
469
470 return t
471
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200472 def render(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200473 """This method accepts the same arguments as the `dict` constructor:
474 A dict, a dict subclass or some keyword arguments. If no arguments
475 are given the context will be empty. These two calls do the same::
476
477 template.render(knights='that say nih')
478 template.render({'knights': 'that say nih'})
479
480 This will return the rendered template as unicode string.
481 """
Armin Ronacherf41d1392008-04-18 16:41:52 +0200482 try:
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200483 return concat(self._generate(*args, **kwargs))
Armin Ronacherf41d1392008-04-18 16:41:52 +0200484 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200485 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200486 exc_type, exc_value, tb = translate_exception(sys.exc_info())
487 raise exc_type, exc_value, tb
Armin Ronacherbcb7c532008-04-11 16:30:34 +0200488
489 def stream(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200490 """Works exactly like :meth:`generate` but returns a
491 :class:`TemplateStream`.
492 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200493 return TemplateStream(self.generate(*args, **kwargs))
Armin Ronacherfed44b52008-04-13 19:42:53 +0200494
495 def generate(self, *args, **kwargs):
Armin Ronacherd1342312008-04-28 12:20:12 +0200496 """For very large templates it can be useful to not render the whole
497 template at once but evaluate each statement after another and yield
498 piece for piece. This method basically does exactly that and returns
499 a generator that yields one item after another as unicode strings.
500
501 It accepts the same arguments as :meth:`render`.
502 """
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200503 try:
504 for item in self._generate(*args, **kwargs):
505 yield item
506 except:
Armin Ronacher27069d72008-05-11 19:48:12 +0200507 from jinja2.debug import translate_exception
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200508 exc_type, exc_value, tb = translate_exception(sys.exc_info())
509 raise exc_type, exc_value, tb
510
511 def _generate(self, *args, **kwargs):
Armin Ronacher981cbf62008-05-13 09:12:27 +0200512 """Creates a new context and generates the template."""
513 return self.root_render_func(self.new_context(dict(*args, **kwargs)))
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200514
Armin Ronacherc9705c22008-04-27 21:28:03 +0200515 def new_context(self, vars=None, shared=False):
516 """Create a new template context for this template. The vars
517 provided will be passed to the template. Per default the globals
518 are added to the context, if shared is set to `True` the data
519 provided is used as parent namespace. This is used to share the
520 same globals in multiple contexts without consuming more memory.
521 (This works because the context does not modify the parent dict)
522 """
523 if vars is None:
524 vars = {}
525 if shared:
526 parent = vars
527 else:
528 parent = dict(self.globals, **vars)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200529 return Context(self.environment, parent, self.name, self.blocks)
Armin Ronacherba3757b2008-04-16 19:43:16 +0200530
Armin Ronacherea847c52008-05-02 20:04:32 +0200531 def make_module(self, vars=None, shared=False):
Armin Ronacher7ceced52008-05-03 10:15:31 +0200532 """This method works like the :attr:`module` attribute when called
533 without arguments but it will evaluate the template every call
534 rather then caching the template. It's also possible to provide
535 a dict which is then used as context. The arguments are the same
536 as fo the :meth:`new_context` method.
Armin Ronacherea847c52008-05-02 20:04:32 +0200537 """
538 return TemplateModule(self, self.new_context(vars, shared))
539
Armin Ronacherd84ec462008-04-29 13:43:16 +0200540 @property
541 def module(self):
542 """The template as module. This is used for imports in the
543 template runtime but is also useful if one wants to access
544 exported template variables from the Python layer:
Armin Ronacherd1342312008-04-28 12:20:12 +0200545
Armin Ronacherd84ec462008-04-29 13:43:16 +0200546 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
547 >>> unicode(t.module)
548 u'23'
549 >>> t.module.foo()
Armin Ronacherd1342312008-04-28 12:20:12 +0200550 u'42'
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200551 """
Armin Ronacherd84ec462008-04-29 13:43:16 +0200552 if hasattr(self, '_module'):
553 return self._module
Armin Ronacherea847c52008-05-02 20:04:32 +0200554 self._module = rv = self.make_module()
Armin Ronacherd84ec462008-04-29 13:43:16 +0200555 return rv
Armin Ronacher963f97d2008-04-25 11:44:59 +0200556
Armin Ronacherba3757b2008-04-16 19:43:16 +0200557 def get_corresponding_lineno(self, lineno):
558 """Return the source line number of a line number in the
559 generated bytecode as they are not in sync.
560 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200561 for template_line, code_line in reversed(self.debug_info):
Armin Ronacherba3757b2008-04-16 19:43:16 +0200562 if code_line <= lineno:
563 return template_line
564 return 1
Armin Ronacherc63243e2008-04-14 22:53:58 +0200565
Armin Ronacher9a822052008-04-17 18:44:07 +0200566 @property
Armin Ronacher814f6c22008-04-17 15:52:23 +0200567 def is_up_to_date(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200568 """If this variable is `False` there is a newer version available."""
Armin Ronacher814f6c22008-04-17 15:52:23 +0200569 if self._uptodate is None:
570 return True
571 return self._uptodate()
572
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200573 @property
574 def debug_info(self):
575 """The debug info mapping."""
576 return [tuple(map(int, x.split('='))) for x in
577 self._debug_info.split('&')]
578
Armin Ronacherc63243e2008-04-14 22:53:58 +0200579 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200580 if self.name is None:
581 name = 'memory:%x' % id(self)
582 else:
583 name = repr(self.name)
584 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacherc63243e2008-04-14 22:53:58 +0200585
586
Armin Ronacherd84ec462008-04-29 13:43:16 +0200587class TemplateModule(object):
588 """Represents an imported template. All the exported names of the
Armin Ronacher53042292008-04-26 18:30:19 +0200589 template are available as attributes on this object. Additionally
590 converting it into an unicode- or bytestrings renders the contents.
591 """
Armin Ronacher963f97d2008-04-25 11:44:59 +0200592
593 def __init__(self, template, context):
Armin Ronacherea847c52008-05-02 20:04:32 +0200594 # don't alter this attribute unless you change it in the
595 # compiler too. The Include without context passing directly
596 # uses the mangled name. The reason why we use a mangled one
597 # is to avoid name clashes with macros with those names.
Armin Ronacher7ceced52008-05-03 10:15:31 +0200598 self.__body_stream = list(template.root_render_func(context))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200599 self.__dict__.update(context.get_exported())
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200600 self.__name__ = template.name
Armin Ronacher963f97d2008-04-25 11:44:59 +0200601
Armin Ronacher53042292008-04-26 18:30:19 +0200602 __html__ = lambda x: Markup(concat(x.__body_stream))
603 __unicode__ = lambda x: unicode(concat(x.__body_stream))
Armin Ronacher6ce170c2008-04-25 12:32:36 +0200604
605 def __str__(self):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200606 return unicode(self).encode('utf-8')
Armin Ronacher963f97d2008-04-25 11:44:59 +0200607
608 def __repr__(self):
Armin Ronacher53042292008-04-26 18:30:19 +0200609 if self.__name__ is None:
610 name = 'memory:%x' % id(self)
611 else:
Armin Ronacherdc02b642008-05-15 22:47:27 +0200612 name = repr(self.__name__)
Armin Ronacher53042292008-04-26 18:30:19 +0200613 return '<%s %s>' % (self.__class__.__name__, name)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200614
615
Armin Ronacherc63243e2008-04-14 22:53:58 +0200616class TemplateStream(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200617 """A template stream works pretty much like an ordinary python generator
618 but it can buffer multiple items to reduce the number of total iterations.
619 Per default the output is unbuffered which means that for every unbuffered
620 instruction in the template one unicode string is yielded.
621
622 If buffering is enabled with a buffer size of 5, five items are combined
623 into a new unicode string. This is mainly useful if you are streaming
624 big templates to a client via WSGI which flushes after each iteration.
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200625 """
Armin Ronacherc63243e2008-04-14 22:53:58 +0200626
627 def __init__(self, gen):
628 self._gen = gen
629 self._next = gen.next
630 self.buffered = False
631
632 def disable_buffering(self):
633 """Disable the output buffering."""
634 self._next = self._gen.next
635 self.buffered = False
636
637 def enable_buffering(self, size=5):
Armin Ronacherd1342312008-04-28 12:20:12 +0200638 """Enable buffering. Buffer `size` items before yielding them."""
Armin Ronacherc63243e2008-04-14 22:53:58 +0200639 if size <= 1:
640 raise ValueError('buffer size too small')
Armin Ronacherc63243e2008-04-14 22:53:58 +0200641
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200642 def generator():
Armin Ronacherc63243e2008-04-14 22:53:58 +0200643 buf = []
644 c_size = 0
645 push = buf.append
646 next = self._gen.next
647
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200648 while 1:
649 try:
Armin Ronacherb5124e62008-04-25 00:36:14 +0200650 while c_size < size:
Armin Ronacher981cbf62008-05-13 09:12:27 +0200651 c = next()
652 push(c)
653 if c:
654 c_size += 1
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200655 except StopIteration:
656 if not c_size:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200657 return
Armin Ronacherde6bf712008-04-26 01:44:14 +0200658 yield concat(buf)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200659 del buf[:]
660 c_size = 0
Armin Ronacherc63243e2008-04-14 22:53:58 +0200661
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200662 self.buffered = True
663 self._next = generator().next
Armin Ronacherc63243e2008-04-14 22:53:58 +0200664
665 def __iter__(self):
666 return self
667
668 def next(self):
669 return self._next()
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200670
671
672# hook in default template class. if anyone reads this comment: ignore that
673# it's possible to use custom templates ;-)
674Environment.template_class = Template