1 # -*- coding: utf-8 -*-
6 Provides a class that holds runtime and parsing time options.
8 :copyright: 2008 by Armin Ronacher.
9 :license: BSD, see LICENSE for more details.
12 from jinja2.defaults import *
13 from jinja2.lexer import Lexer
14 from jinja2.parser import Parser
15 from jinja2.optimizer import optimize
16 from jinja2.compiler import generate
17 from jinja2.runtime import Undefined, Context, concat
18 from jinja2.debug import translate_exception, translate_syntax_error
19 from jinja2.exceptions import TemplateSyntaxError
20 from jinja2.utils import import_string, LRUCache, Markup, missing
23 # for direct template usage we have up to ten living environments
24 _spontaneous_environments = LRUCache(10)
27 def get_spontaneous_environment(*args):
28 """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.
33 env = _spontaneous_environments.get(args)
35 return Environment(*args)
38 _spontaneous_environments[args] = env = Environment(*args)
43 def create_cache(size):
44 """Return the cache class for the given size."""
52 def load_extensions(environment, extensions):
53 """Load the extensions from the list and bind it to the environment.
54 Returns a new list of instanciated environments.
57 for extension in extensions:
58 if isinstance(extension, basestring):
59 extension = import_string(extension)
60 result.append(extension(environment))
64 def _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'
75 class Environment(object):
76 """The core component of Jinja is the `Environment`. It contains
77 important shared variables like configuration, filters, tests,
78 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.
83 Here the possible initialization parameters:
86 The string marking the begin of a block. Defaults to ``'{%'``.
89 The string marking the end of a block. Defaults to ``'%}'``.
91 `variable_start_string`
92 The string marking the begin of a print statement.
95 `variable_stop_string`
96 The string marking the end of a print statement. Defaults to ``'}}'``.
98 `comment_start_string`
99 The string marking the begin of a comment. Defaults to ``'{#'``.
102 The string marking the end of a comment. Defaults to ``'#}'``.
104 `line_statement_prefix`
105 If given and a string, this will be used as prefix for line based
109 If this is set to ``True`` the first newline after a block is
110 removed (block, not variable tag!). Defaults to `False`.
113 List of Jinja extensions to use. This can either be import paths
114 as strings or extension classes.
117 should the optimizer be enabled? Default is `True`.
120 :class:`Undefined` or a subclass of it that is used to represent
121 undefined values in the template.
124 A callable that finalizes the variable. Per default no finalizing
128 If set to true the XML/HTML autoescaping feature is enabled.
131 The template loader for this environment.
134 The size of the cache. Per default this is ``50`` which means that if
135 more than 50 templates are loaded the loader will clean out the least
136 recently used template. If the cache size is set to ``0`` templates are
137 recompiled all the time, if the cache size is ``-1`` the cache will not
141 Some loaders load templates from locations where the template sources
142 may change (ie: file system or database). If `auto_reload` is set to
143 `True` (default) every time a template is requested the loader checks
144 if the source changed and if yes, it will reload the template. For
145 higher performance it's possible to disable that.
148 #: if this environment is sandboxed. Modifying this variable won't make
149 #: the environment sandboxed though. For a real sandboxed environment
150 #: have a look at jinja2.sandbox
153 #: True if the environment is just an overlay
156 #: the environment this environment is linked to if it is an overlay
159 #: shared environments have this set to `True`. A shared environment
160 #: must not be modified
164 block_start_string=BLOCK_START_STRING,
165 block_end_string=BLOCK_END_STRING,
166 variable_start_string=VARIABLE_START_STRING,
167 variable_end_string=VARIABLE_END_STRING,
168 comment_start_string=COMMENT_START_STRING,
169 comment_end_string=COMMENT_END_STRING,
170 line_statement_prefix=LINE_STATEMENT_PREFIX,
180 # !!Important notice!!
181 # The constructor accepts quite a few arguments that should be
182 # passed by keyword rather than position. However it's important to
183 # not change the order of arguments because it's used at least
184 # internally in those cases:
185 # - spontaneus environments (i18n extension and Template)
187 # If parameter changes are required only add parameters at the end
188 # and don't change the arguments (or the defaults!) of the arguments
191 # lexer / parser information
192 self.block_start_string = block_start_string
193 self.block_end_string = block_end_string
194 self.variable_start_string = variable_start_string
195 self.variable_end_string = variable_end_string
196 self.comment_start_string = comment_start_string
197 self.comment_end_string = comment_end_string
198 self.line_statement_prefix = line_statement_prefix
199 self.trim_blocks = trim_blocks
201 # runtime information
202 self.undefined = undefined
203 self.optimized = optimized
204 self.finalize = finalize
205 self.autoescape = autoescape
208 self.filters = DEFAULT_FILTERS.copy()
209 self.tests = DEFAULT_TESTS.copy()
210 self.globals = DEFAULT_NAMESPACE.copy()
212 # set the loader provided
214 self.cache = create_cache(cache_size)
215 self.auto_reload = auto_reload
218 self.extensions = load_extensions(self, extensions)
220 _environment_sanity_check(self)
222 def overlay(self, block_start_string=missing, block_end_string=missing,
223 variable_start_string=missing, variable_end_string=missing,
224 comment_start_string=missing, comment_end_string=missing,
225 line_statement_prefix=missing, trim_blocks=missing,
226 extensions=missing, optimized=missing, undefined=missing,
227 finalize=missing, autoescape=missing, loader=missing,
228 cache_size=missing, auto_reload=missing):
229 """Create a new overlay environment that shares all the data with the
230 current environment except of cache and the overriden attributes.
231 Extensions cannot be removed for a overlayed environment. A overlayed
232 environment automatically gets all the extensions of the environment it
233 is linked to plus optional extra extensions.
235 Creating overlays should happen after the initial environment was set
236 up completely. Not all attributes are truly linked, some are just
237 copied over so modifications on the original environment may not shine
240 args = dict(locals())
241 del args['self'], args['cache_size'], args['extensions']
243 rv = object.__new__(self.__class__)
244 rv.__dict__.update(self.__dict__)
248 for key, value in args.iteritems():
249 if value is not missing:
250 setattr(rv, key, value)
252 if cache_size is not missing:
253 rv.cache = create_cache(cache_size)
256 for extension in self.extensions:
257 rv.extensions.append(extension.bind(self))
258 if extensions is not missing:
259 rv.extensions.extend(load_extensions(extensions))
261 return _environment_sanity_check(rv)
265 """Return a fresh lexer for the environment."""
268 def subscribe(self, obj, argument):
269 """Get an item or attribute of an object."""
271 return getattr(obj, str(argument))
272 except (AttributeError, UnicodeError):
275 except (TypeError, LookupError):
276 return self.undefined(obj=obj, name=argument)
278 def parse(self, source, filename=None):
279 """Parse the sourcecode and return the abstract syntax tree. This
280 tree of nodes is used by the compiler to convert the template into
281 executable source- or bytecode. This is useful for debugging or to
282 extract information from templates.
285 return Parser(self, source, filename).parse()
286 except TemplateSyntaxError, e:
288 exc_type, exc_value, tb = translate_syntax_error(e)
289 raise exc_type, exc_value, tb
291 def lex(self, source, name=None):
292 """Lex the given sourcecode and return a generator that yields
293 tokens as tuples in the form ``(lineno, token_type, value)``.
295 return self.lexer.tokeniter(source, name)
297 def compile(self, source, name=None, filename=None, globals=None,
299 """Compile a node or template source code. The `name` parameter is
300 the load name of the template after it was joined using
301 :meth:`join_path` if necessary, not the filename on the file system.
302 the `filename` parameter is the estimated filename of the template on
303 the file system. If the template came from a database or memory this
304 can be omitted. The `globals` parameter can be used to provide extra
305 variables at compile time for the template. In the future the
306 optimizer will be able to evaluate parts of the template at compile
307 time based on those variables.
309 The return value of this method is a python code object. If the `raw`
310 parameter is `True` the return value will be a string with python
311 code equivalent to the bytecode returned otherwise. This method is
312 mainly used internally.
314 if isinstance(source, basestring):
315 source = self.parse(source, filename)
317 node = optimize(source, self, globals or {})
318 source = generate(node, self, name, filename)
322 filename = '<template>'
323 elif isinstance(filename, unicode):
324 filename = filename.encode('utf-8')
325 return compile(source, filename, 'exec')
327 def join_path(self, template, parent):
328 """Join a template with the parent. By default all the lookups are
329 relative to the loader root so this method returns the `template`
330 parameter unchanged, but if the paths should be relative to the
331 parent template, this function can be used to calculate the real
334 Subclasses may override this method and implement template path
339 def get_template(self, name, parent=None, globals=None):
340 """Load a template from the loader. If a loader is configured this
341 method ask the loader for the template and returns a :class:`Template`.
342 If the `parent` parameter is not `None`, :meth:`join_path` is called
343 to get the real template name before loading.
345 The `globals` parameter can be used to provide compile-time globals.
346 In the future this will allow the optimizer to render parts of the
347 templates at compile-time.
349 If the template does not exist a :exc:`TemplateNotFound` exception is
352 if self.loader is None:
353 raise TypeError('no loader for this environment specified')
354 if parent is not None:
355 name = self.join_path(name, parent)
357 if self.cache is not None:
358 template = self.cache.get(name)
359 if template is not None and (not self.auto_reload or \
360 template.is_up_to_date):
363 template = self.loader.load(self, name, self.make_globals(globals))
364 if self.cache is not None:
365 self.cache[name] = template
368 def from_string(self, source, globals=None, template_class=None):
369 """Load a template from a string. This parses the source given and
370 returns a :class:`Template` object.
372 globals = self.make_globals(globals)
373 cls = template_class or self.template_class
374 return cls.from_code(self, self.compile(source, globals=globals),
377 def make_globals(self, d):
378 """Return a dict for the globals."""
381 return dict(self.globals, **d)
384 class Template(object):
385 """The central template object. This class represents a compiled template
386 and is used to evaluate it.
388 Normally the template object is generated from an :class:`Environment` but
389 it also has a constructor that makes it possible to create a template
390 instance directly using the constructor. It takes the same arguments as
391 the environment constructor but it's not possible to specify a loader.
393 Every template object has a few methods and members that are guaranteed
394 to exist. However it's important that a template object should be
395 considered immutable. Modifications on the object are not supported.
397 Template objects created from the constructor rather than an environment
398 do have an `environment` attribute that points to a temporary environment
399 that is probably shared with other templates created with the constructor
400 and compatible settings.
402 >>> template = Template('Hello {{ name }}!')
403 >>> template.render(name='John Doe')
406 >>> stream = template.stream(name='John Doe')
410 Traceback (most recent call last):
415 def __new__(cls, source,
416 block_start_string='{%',
417 block_end_string='%}',
418 variable_start_string='{{',
419 variable_end_string='}}',
420 comment_start_string='{#',
421 comment_end_string='#}',
422 line_statement_prefix=None,
429 env = get_spontaneous_environment(
430 block_start_string, block_end_string, variable_start_string,
431 variable_end_string, comment_start_string, comment_end_string,
432 line_statement_prefix, trim_blocks, tuple(extensions), optimized,
433 undefined, finalize, autoescape, None, 0, False)
434 return env.from_string(source, template_class=cls)
437 def from_code(cls, environment, code, globals, uptodate=None):
438 """Creates a template object from compiled code and the globals. This
439 is used by the loaders and environment to create a template object.
441 t = object.__new__(cls)
443 'environment': environment,
444 '__jinja_template__': t
446 exec code in namespace
447 t.environment = environment
448 t.name = namespace['name']
449 t.filename = code.co_filename
450 t.root_render_func = namespace['root']
451 t.blocks = namespace['blocks']
454 # debug and loader helpers
455 t._debug_info = namespace['debug_info']
456 t._uptodate = uptodate
460 def render(self, *args, **kwargs):
461 """This method accepts the same arguments as the `dict` constructor:
462 A dict, a dict subclass or some keyword arguments. If no arguments
463 are given the context will be empty. These two calls do the same::
465 template.render(knights='that say nih')
466 template.render({'knights': 'that say nih'})
468 This will return the rendered template as unicode string.
471 return concat(self._generate(*args, **kwargs))
473 exc_type, exc_value, tb = translate_exception(sys.exc_info())
474 raise exc_type, exc_value, tb
476 def stream(self, *args, **kwargs):
477 """Works exactly like :meth:`generate` but returns a
478 :class:`TemplateStream`.
480 return TemplateStream(self.generate(*args, **kwargs))
482 def generate(self, *args, **kwargs):
483 """For very large templates it can be useful to not render the whole
484 template at once but evaluate each statement after another and yield
485 piece for piece. This method basically does exactly that and returns
486 a generator that yields one item after another as unicode strings.
488 It accepts the same arguments as :meth:`render`.
491 for item in self._generate(*args, **kwargs):
494 exc_type, exc_value, tb = translate_exception(sys.exc_info())
495 raise exc_type, exc_value, tb
497 def _generate(self, *args, **kwargs):
498 # assemble the context
499 context = dict(*args, **kwargs)
501 # if the environment is using the optimizer locals may never
502 # override globals as optimizations might have happened
503 # depending on values of certain globals. This assertion goes
504 # away if the python interpreter is started with -O
505 if __debug__ and self.environment.optimized:
506 overrides = set(context) & set(self.globals)
508 plural = len(overrides) != 1 and 's' or ''
509 raise AssertionError('the per template variable%s %s '
510 'override%s global variable%s. '
511 'With an enabled optimizer this '
512 'will lead to unexpected results.' %
513 (plural, ', '.join(overrides), plural or ' a', plural))
515 return self.root_render_func(self.new_context(context))
517 def new_context(self, vars=None, shared=False):
518 """Create a new template context for this template. The vars
519 provided will be passed to the template. Per default the globals
520 are added to the context, if shared is set to `True` the data
521 provided is used as parent namespace. This is used to share the
522 same globals in multiple contexts without consuming more memory.
523 (This works because the context does not modify the parent dict)
530 parent = dict(self.globals, **vars)
531 return Context(self.environment, parent, self.name, self.blocks)
535 """The template as module. This is used for imports in the
536 template runtime but is also useful if one wants to access
537 exported template variables from the Python layer:
539 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
540 >>> unicode(t.module)
545 if hasattr(self, '_module'):
547 self._module = rv = TemplateModule(self, self.new_context())
550 def get_corresponding_lineno(self, lineno):
551 """Return the source line number of a line number in the
552 generated bytecode as they are not in sync.
554 for template_line, code_line in reversed(self.debug_info):
555 if code_line <= lineno:
560 def is_up_to_date(self):
561 """If this variable is `False` there is a newer version available."""
562 if self._uptodate is None:
564 return self._uptodate()
567 def debug_info(self):
568 """The debug info mapping."""
569 return [tuple(map(int, x.split('='))) for x in
570 self._debug_info.split('&')]
573 if self.name is None:
574 name = 'memory:%x' % id(self)
576 name = repr(self.name)
577 return '<%s %s>' % (self.__class__.__name__, name)
580 class TemplateModule(object):
581 """Represents an imported template. All the exported names of the
582 template are available as attributes on this object. Additionally
583 converting it into an unicode- or bytestrings renders the contents.
586 def __init__(self, template, context):
587 self.__body_stream = tuple(template.root_render_func(context))
588 self.__dict__.update(context.get_exported())
589 self.__name__ = template.name
591 __html__ = lambda x: Markup(concat(x.__body_stream))
592 __unicode__ = lambda x: unicode(concat(x.__body_stream))
595 return unicode(self).encode('utf-8')
598 if self.__name__ is None:
599 name = 'memory:%x' % id(self)
601 name = repr(self.name)
602 return '<%s %s>' % (self.__class__.__name__, name)
605 class TemplateStream(object):
606 """A template stream works pretty much like an ordinary python generator
607 but it can buffer multiple items to reduce the number of total iterations.
608 Per default the output is unbuffered which means that for every unbuffered
609 instruction in the template one unicode string is yielded.
611 If buffering is enabled with a buffer size of 5, five items are combined
612 into a new unicode string. This is mainly useful if you are streaming
613 big templates to a client via WSGI which flushes after each iteration.
616 def __init__(self, gen):
618 self._next = gen.next
619 self.buffered = False
621 def disable_buffering(self):
622 """Disable the output buffering."""
623 self._next = self._gen.next
624 self.buffered = False
626 def enable_buffering(self, size=5):
627 """Enable buffering. Buffer `size` items before yielding them."""
629 raise ValueError('buffer size too small')
635 next = self._gen.next
642 except StopIteration:
650 self._next = generator().next
659 # hook in default template class. if anyone reads this comment: ignore that
660 # it's possible to use custom templates ;-)
661 Environment.template_class = Template