1 # -*- coding: utf-8 -*-
6 Provides a class that holds runtime and parsing time options.
8 :copyright: (c) 2010 by the Jinja Team.
9 :license: BSD, see LICENSE for more details.
13 from jinja2 import nodes
14 from jinja2.defaults import *
15 from jinja2.lexer import get_lexer, TokenStream
16 from jinja2.parser import Parser
17 from jinja2.optimizer import optimize
18 from jinja2.compiler import generate
19 from jinja2.runtime import Undefined, new_context
20 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \
22 from jinja2.utils import import_string, LRUCache, Markup, missing, \
23 concat, consume, internalcode, _encode_filename
26 # for direct template usage we have up to ten living environments
27 _spontaneous_environments = LRUCache(10)
29 # the function to create jinja traceback objects. This is dynamically
30 # imported on the first exception in the exception handler.
31 _make_traceback = None
34 def get_spontaneous_environment(*args):
35 """Return a new spontaneous environment. A spontaneous environment is an
36 unnamed and unaccessible (in theory) environment that is used for
37 templates generated from a string and not from the file system.
40 env = _spontaneous_environments.get(args)
42 return Environment(*args)
45 _spontaneous_environments[args] = env = Environment(*args)
50 def create_cache(size):
51 """Return the cache class for the given size."""
59 def copy_cache(cache):
60 """Create an empty copy of the given cache."""
63 elif type(cache) is dict:
65 return LRUCache(cache.capacity)
68 def load_extensions(environment, extensions):
69 """Load the extensions from the list and bind it to the environment.
70 Returns a dict of instanciated environments.
73 for extension in extensions:
74 if isinstance(extension, basestring):
75 extension = import_string(extension)
76 result[extension.identifier] = extension(environment)
80 def _environment_sanity_check(environment):
81 """Perform a sanity check on the environment."""
82 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
83 'be a subclass of undefined because filters depend on it.'
84 assert environment.block_start_string != \
85 environment.variable_start_string != \
86 environment.comment_start_string, 'block, variable and comment ' \
87 'start strings must be different'
88 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
89 'newline_sequence set to unknown line ending string.'
93 class Environment(object):
94 r"""The core component of Jinja is the `Environment`. It contains
95 important shared variables like configuration, filters, tests,
96 globals and others. Instances of this class may be modified if
97 they are not shared and if no template was loaded so far.
98 Modifications on environments after the first template was loaded
99 will lead to surprising effects and undefined behavior.
101 Here the possible initialization parameters:
104 The string marking the begin of a block. Defaults to ``'{%'``.
107 The string marking the end of a block. Defaults to ``'%}'``.
109 `variable_start_string`
110 The string marking the begin of a print statement.
111 Defaults to ``'{{'``.
113 `variable_end_string`
114 The string marking the end of a print statement. Defaults to
117 `comment_start_string`
118 The string marking the begin of a comment. Defaults to ``'{#'``.
121 The string marking the end of a comment. Defaults to ``'#}'``.
123 `line_statement_prefix`
124 If given and a string, this will be used as prefix for line based
125 statements. See also :ref:`line-statements`.
127 `line_comment_prefix`
128 If given and a string, this will be used as prefix for line based
129 based comments. See also :ref:`line-statements`.
131 .. versionadded:: 2.2
134 If this is set to ``True`` the first newline after a block is
135 removed (block, not variable tag!). Defaults to `False`.
138 The sequence that starts a newline. Must be one of ``'\r'``,
139 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
140 useful default for Linux and OS X systems as well as web
144 List of Jinja extensions to use. This can either be import paths
145 as strings or extension classes. For more information have a
146 look at :ref:`the extensions documentation <jinja-extensions>`.
149 should the optimizer be enabled? Default is `True`.
152 :class:`Undefined` or a subclass of it that is used to represent
153 undefined values in the template.
156 A callable that can be used to process the result of a variable
157 expression before it is output. For example one can convert
158 `None` implicitly into an empty string here.
161 If set to true the XML/HTML autoescaping feature is enabled by
162 default. For more details about auto escaping see
163 :class:`~jinja2.utils.Markup`.
166 The template loader for this environment.
169 The size of the cache. Per default this is ``50`` which means
170 that if more than 50 templates are loaded the loader will clean
171 out the least recently used template. If the cache size is set to
172 ``0`` templates are recompiled all the time, if the cache size is
173 ``-1`` the cache will not be cleaned.
176 Some loaders load templates from locations where the template
177 sources may change (ie: file system or database). If
178 `auto_reload` is set to `True` (default) every time a template is
179 requested the loader checks if the source changed and if yes, it
180 will reload the template. For higher performance it's possible to
184 If set to a bytecode cache object, this object will provide a
185 cache for the internal Jinja bytecode so that templates don't
186 have to be parsed if they were not changed.
188 See :ref:`bytecode-cache` for more information.
191 #: if this environment is sandboxed. Modifying this variable won't make
192 #: the environment sandboxed though. For a real sandboxed environment
193 #: have a look at jinja2.sandbox
196 #: True if the environment is just an overlay
199 #: the environment this environment is linked to if it is an overlay
202 #: shared environments have this set to `True`. A shared environment
203 #: must not be modified
206 #: these are currently EXPERIMENTAL undocumented features.
207 exception_handler = None
208 exception_formatter = None
211 block_start_string=BLOCK_START_STRING,
212 block_end_string=BLOCK_END_STRING,
213 variable_start_string=VARIABLE_START_STRING,
214 variable_end_string=VARIABLE_END_STRING,
215 comment_start_string=COMMENT_START_STRING,
216 comment_end_string=COMMENT_END_STRING,
217 line_statement_prefix=LINE_STATEMENT_PREFIX,
218 line_comment_prefix=LINE_COMMENT_PREFIX,
219 trim_blocks=TRIM_BLOCKS,
220 newline_sequence=NEWLINE_SEQUENCE,
229 bytecode_cache=None):
230 # !!Important notice!!
231 # The constructor accepts quite a few arguments that should be
232 # passed by keyword rather than position. However it's important to
233 # not change the order of arguments because it's used at least
234 # internally in those cases:
235 # - spontaneus environments (i18n extension and Template)
237 # If parameter changes are required only add parameters at the end
238 # and don't change the arguments (or the defaults!) of the arguments
241 # lexer / parser information
242 self.block_start_string = block_start_string
243 self.block_end_string = block_end_string
244 self.variable_start_string = variable_start_string
245 self.variable_end_string = variable_end_string
246 self.comment_start_string = comment_start_string
247 self.comment_end_string = comment_end_string
248 self.line_statement_prefix = line_statement_prefix
249 self.line_comment_prefix = line_comment_prefix
250 self.trim_blocks = trim_blocks
251 self.newline_sequence = newline_sequence
253 # runtime information
254 self.undefined = undefined
255 self.optimized = optimized
256 self.finalize = finalize
257 self.autoescape = autoescape
260 self.filters = DEFAULT_FILTERS.copy()
261 self.tests = DEFAULT_TESTS.copy()
262 self.globals = DEFAULT_NAMESPACE.copy()
264 # set the loader provided
266 self.bytecode_cache = None
267 self.cache = create_cache(cache_size)
268 self.bytecode_cache = bytecode_cache
269 self.auto_reload = auto_reload
272 self.extensions = load_extensions(self, extensions)
274 _environment_sanity_check(self)
276 def extend(self, **attributes):
277 """Add the items to the instance of the environment if they do not exist
278 yet. This is used by :ref:`extensions <writing-extensions>` to register
279 callbacks and configuration values without breaking inheritance.
281 for key, value in attributes.iteritems():
282 if not hasattr(self, key):
283 setattr(self, key, value)
285 def overlay(self, block_start_string=missing, block_end_string=missing,
286 variable_start_string=missing, variable_end_string=missing,
287 comment_start_string=missing, comment_end_string=missing,
288 line_statement_prefix=missing, line_comment_prefix=missing,
289 trim_blocks=missing, extensions=missing, optimized=missing,
290 undefined=missing, finalize=missing, autoescape=missing,
291 loader=missing, cache_size=missing, auto_reload=missing,
292 bytecode_cache=missing):
293 """Create a new overlay environment that shares all the data with the
294 current environment except of cache and the overridden attributes.
295 Extensions cannot be removed for an overlayed environment. An overlayed
296 environment automatically gets all the extensions of the environment it
297 is linked to plus optional extra extensions.
299 Creating overlays should happen after the initial environment was set
300 up completely. Not all attributes are truly linked, some are just
301 copied over so modifications on the original environment may not shine
304 args = dict(locals())
305 del args['self'], args['cache_size'], args['extensions']
307 rv = object.__new__(self.__class__)
308 rv.__dict__.update(self.__dict__)
312 for key, value in args.iteritems():
313 if value is not missing:
314 setattr(rv, key, value)
316 if cache_size is not missing:
317 rv.cache = create_cache(cache_size)
319 rv.cache = copy_cache(self.cache)
322 for key, value in self.extensions.iteritems():
323 rv.extensions[key] = value.bind(rv)
324 if extensions is not missing:
325 rv.extensions.update(load_extensions(extensions))
327 return _environment_sanity_check(rv)
329 lexer = property(get_lexer, doc="The lexer for this environment.")
331 def getitem(self, obj, argument):
332 """Get an item or attribute of an object but prefer the item."""
335 except (TypeError, LookupError):
336 if isinstance(argument, basestring):
343 return getattr(obj, attr)
344 except AttributeError:
346 return self.undefined(obj=obj, name=argument)
348 def getattr(self, obj, attribute):
349 """Get an item or attribute of an object but prefer the attribute.
350 Unlike :meth:`getitem` the attribute *must* be a bytestring.
353 return getattr(obj, attribute)
354 except AttributeError:
357 return obj[attribute]
358 except (TypeError, LookupError, AttributeError):
359 return self.undefined(obj=obj, name=attribute)
362 def parse(self, source, name=None, filename=None):
363 """Parse the sourcecode and return the abstract syntax tree. This
364 tree of nodes is used by the compiler to convert the template into
365 executable source- or bytecode. This is useful for debugging or to
366 extract information from templates.
368 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
369 this gives you a good overview of the node tree generated.
372 return self._parse(source, name, filename)
373 except TemplateSyntaxError:
374 exc_info = sys.exc_info()
375 self.handle_exception(exc_info, source_hint=source)
377 def _parse(self, source, name, filename):
378 """Internal parsing function used by `parse` and `compile`."""
379 return Parser(self, source, name, _encode_filename(filename)).parse()
381 def lex(self, source, name=None, filename=None):
382 """Lex the given sourcecode and return a generator that yields
383 tokens as tuples in the form ``(lineno, token_type, value)``.
384 This can be useful for :ref:`extension development <writing-extensions>`
385 and debugging templates.
387 This does not perform preprocessing. If you want the preprocessing
388 of the extensions to be applied you have to filter source through
389 the :meth:`preprocess` method.
391 source = unicode(source)
393 return self.lexer.tokeniter(source, name, filename)
394 except TemplateSyntaxError:
395 exc_info = sys.exc_info()
396 self.handle_exception(exc_info, source_hint=source)
398 def preprocess(self, source, name=None, filename=None):
399 """Preprocesses the source with all extensions. This is automatically
400 called for all parsing and compiling methods but *not* for :meth:`lex`
401 because there you usually only want the actual source tokenized.
403 return reduce(lambda s, e: e.preprocess(s, name, filename),
404 self.extensions.itervalues(), unicode(source))
406 def _tokenize(self, source, name, filename=None, state=None):
407 """Called by the parser to do the preprocessing and filtering
408 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
410 source = self.preprocess(source, name, filename)
411 stream = self.lexer.tokenize(source, name, filename, state)
412 for ext in self.extensions.itervalues():
413 stream = ext.filter_stream(stream)
414 if not isinstance(stream, TokenStream):
415 stream = TokenStream(stream, name, filename)
419 def compile(self, source, name=None, filename=None, raw=False,
421 """Compile a node or template source code. The `name` parameter is
422 the load name of the template after it was joined using
423 :meth:`join_path` if necessary, not the filename on the file system.
424 the `filename` parameter is the estimated filename of the template on
425 the file system. If the template came from a database or memory this
428 The return value of this method is a python code object. If the `raw`
429 parameter is `True` the return value will be a string with python
430 code equivalent to the bytecode returned otherwise. This method is
431 mainly used internally.
433 `defer_init` is use internally to aid the module code generator. This
434 causes the generated code to be able to import without the global
435 environment variable to be set.
437 .. versionadded:: 2.4
438 `defer_init` parameter added.
442 if isinstance(source, basestring):
444 source = self._parse(source, name, filename)
446 source = optimize(source, self)
447 source = generate(source, self, name, filename,
448 defer_init=defer_init)
452 filename = '<template>'
454 filename = _encode_filename(filename)
455 return compile(source, filename, 'exec')
456 except TemplateSyntaxError:
457 exc_info = sys.exc_info()
458 self.handle_exception(exc_info, source_hint=source)
460 def compile_expression(self, source, undefined_to_none=True):
461 """A handy helper method that returns a callable that accepts keyword
462 arguments that appear as variables in the expression. If called it
463 returns the result of the expression.
465 This is useful if applications want to use the same rules as Jinja
466 in template "configuration files" or similar situations.
470 >>> env = Environment()
471 >>> expr = env.compile_expression('foo == 42')
477 Per default the return value is converted to `None` if the
478 expression returns an undefined value. This can be changed
479 by setting `undefined_to_none` to `False`.
481 >>> env.compile_expression('var')() is None
483 >>> env.compile_expression('var', undefined_to_none=False)()
486 .. versionadded:: 2.1
488 parser = Parser(self, source, state='variable')
491 expr = parser.parse_expression()
492 if not parser.stream.eos:
493 raise TemplateSyntaxError('chunk after expression',
494 parser.stream.current.lineno,
496 expr.set_environment(self)
497 except TemplateSyntaxError:
498 exc_info = sys.exc_info()
499 if exc_info is not None:
500 self.handle_exception(exc_info, source_hint=source)
501 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
502 template = self.from_string(nodes.Template(body, lineno=1))
503 return TemplateExpression(template, undefined_to_none)
505 def compile_templates(self, target, extensions=None, filter_func=None,
506 zip='deflated', log_function=None,
507 ignore_errors=True, py_compile=False):
508 """Compiles all the templates the loader can find, compiles them
509 and stores them in `target`. If `zip` is `None`, instead of in a
510 zipfile, the templates will be will be stored in a directory.
511 By default a deflate zip algorithm is used, to switch to
512 the stored algorithm, `zip` can be set to ``'stored'``.
514 `extensions` and `filter_func` are passed to :meth:`list_templates`.
515 Each template returned will be compiled to the target folder or
518 By default template compilation errors are ignored. In case a
519 log function is provided, errors are logged. If you want template
520 syntax errors to abort the compilation you can set `ignore_errors`
521 to `False` and you will get an exception on syntax errors.
523 If `py_compile` is set to `True` .pyc files will be written to the
524 target instead of standard .py files.
526 .. versionadded:: 2.4
528 from jinja2.loaders import ModuleLoader
530 if log_function is None:
531 log_function = lambda x: None
534 import imp, struct, marshal
535 py_header = imp.get_magic() + \
536 u'\xff\xff\xff\xff'.encode('iso-8859-15')
538 def write_file(filename, data, mode):
540 info = ZipInfo(filename)
541 info.external_attr = 0755 << 16L
542 zip_file.writestr(info, data)
544 f = open(os.path.join(target, filename), mode)
551 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
552 zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED,
553 stored=ZIP_STORED)[zip])
554 log_function('Compiling into Zip archive "%s"' % target)
556 if not os.path.isdir(target):
558 log_function('Compiling into folder "%s"' % target)
561 for name in self.list_templates(extensions, filter_func):
562 source, filename, _ = self.loader.get_source(self, name)
564 code = self.compile(source, name, filename, True, True)
565 except TemplateSyntaxError, e:
566 if not ignore_errors:
568 log_function('Could not compile "%s": %s' % (name, e))
571 filename = ModuleLoader.get_module_filename(name)
574 c = compile(code, _encode_filename(filename), 'exec')
575 write_file(filename + 'c', py_header +
576 marshal.dumps(c), 'wb')
577 log_function('Byte-compiled "%s" as %s' %
578 (name, filename + 'c'))
580 write_file(filename, code, 'w')
581 log_function('Compiled "%s" as %s' % (name, filename))
586 log_function('Finished compiling templates')
588 def list_templates(self, extensions=None, filter_func=None):
589 """Returns a list of templates for this environment. This requires
590 that the loader supports the loader's
591 :meth:`~BaseLoader.list_templates` method.
593 If there are other files in the template folder besides the
594 actual templates, the returned list can be filtered. There are two
595 ways: either `extensions` is set to a list of file extensions for
596 templates, or a `filter_func` can be provided which is a callable that
597 is passed a template name and should return `True` if it should end up
600 If the loader does not support that, a :exc:`TypeError` is raised.
602 x = self.loader.list_templates()
603 if extensions is not None:
604 if filter_func is not None:
605 raise TypeError('either extensions or filter_func '
606 'can be passed, but not both')
607 filter_func = lambda x: '.' in x and \
608 x.rsplit('.', 1)[1] in extensions
609 if filter_func is not None:
610 x = filter(filter_func, x)
613 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
614 """Exception handling helper. This is used internally to either raise
615 rewritten exceptions or return a rendered traceback for the template.
617 global _make_traceback
619 exc_info = sys.exc_info()
621 # the debugging module is imported when it's used for the first time.
622 # we're doing a lot of stuff there and for applications that do not
623 # get any exceptions in template rendering there is no need to load
625 if _make_traceback is None:
626 from jinja2.debug import make_traceback as _make_traceback
627 traceback = _make_traceback(exc_info, source_hint)
628 if rendered and self.exception_formatter is not None:
629 return self.exception_formatter(traceback)
630 if self.exception_handler is not None:
631 self.exception_handler(traceback)
632 exc_type, exc_value, tb = traceback.standard_exc_info
633 raise exc_type, exc_value, tb
635 def join_path(self, template, parent):
636 """Join a template with the parent. By default all the lookups are
637 relative to the loader root so this method returns the `template`
638 parameter unchanged, but if the paths should be relative to the
639 parent template, this function can be used to calculate the real
642 Subclasses may override this method and implement template path
648 def _load_template(self, name, globals):
649 if self.loader is None:
650 raise TypeError('no loader for this environment specified')
651 if self.cache is not None:
652 template = self.cache.get(name)
653 if template is not None and (not self.auto_reload or \
654 template.is_up_to_date):
656 template = self.loader.load(self, name, globals)
657 if self.cache is not None:
658 self.cache[name] = template
662 def get_template(self, name, parent=None, globals=None):
663 """Load a template from the loader. If a loader is configured this
664 method ask the loader for the template and returns a :class:`Template`.
665 If the `parent` parameter is not `None`, :meth:`join_path` is called
666 to get the real template name before loading.
668 The `globals` parameter can be used to provide template wide globals.
669 These variables are available in the context at render time.
671 If the template does not exist a :exc:`TemplateNotFound` exception is
674 .. versionchanged:: 2.4
675 If `name` is a :class:`Template` object it is returned from the
678 if isinstance(name, Template):
680 if parent is not None:
681 name = self.join_path(name, parent)
682 return self._load_template(name, self.make_globals(globals))
685 def select_template(self, names, parent=None, globals=None):
686 """Works like :meth:`get_template` but tries a number of templates
687 before it fails. If it cannot find any of the templates, it will
688 raise a :exc:`TemplatesNotFound` exception.
690 .. versionadded:: 2.3
692 .. versionchanged:: 2.4
693 If `names` contains a :class:`Template` object it is returned
694 from the function unchanged.
697 raise TemplatesNotFound(message=u'Tried to select from an empty list '
699 globals = self.make_globals(globals)
701 if isinstance(name, Template):
703 if parent is not None:
704 name = self.join_path(name, parent)
706 return self._load_template(name, globals)
707 except TemplateNotFound:
709 raise TemplatesNotFound(names)
712 def get_or_select_template(self, template_name_or_list,
713 parent=None, globals=None):
714 """Does a typecheck and dispatches to :meth:`select_template`
715 if an iterable of template names is given, otherwise to
716 :meth:`get_template`.
718 .. versionadded:: 2.3
720 if isinstance(template_name_or_list, basestring):
721 return self.get_template(template_name_or_list, parent, globals)
722 elif isinstance(template_name_or_list, Template):
723 return template_name_or_list
724 return self.select_template(template_name_or_list, parent, globals)
726 def from_string(self, source, globals=None, template_class=None):
727 """Load a template from a string. This parses the source given and
728 returns a :class:`Template` object.
730 globals = self.make_globals(globals)
731 cls = template_class or self.template_class
732 return cls.from_code(self, self.compile(source), globals, None)
734 def make_globals(self, d):
735 """Return a dict for the globals."""
738 return dict(self.globals, **d)
741 class Template(object):
742 """The central template object. This class represents a compiled template
743 and is used to evaluate it.
745 Normally the template object is generated from an :class:`Environment` but
746 it also has a constructor that makes it possible to create a template
747 instance directly using the constructor. It takes the same arguments as
748 the environment constructor but it's not possible to specify a loader.
750 Every template object has a few methods and members that are guaranteed
751 to exist. However it's important that a template object should be
752 considered immutable. Modifications on the object are not supported.
754 Template objects created from the constructor rather than an environment
755 do have an `environment` attribute that points to a temporary environment
756 that is probably shared with other templates created with the constructor
757 and compatible settings.
759 >>> template = Template('Hello {{ name }}!')
760 >>> template.render(name='John Doe')
763 >>> stream = template.stream(name='John Doe')
767 Traceback (most recent call last):
772 def __new__(cls, source,
773 block_start_string=BLOCK_START_STRING,
774 block_end_string=BLOCK_END_STRING,
775 variable_start_string=VARIABLE_START_STRING,
776 variable_end_string=VARIABLE_END_STRING,
777 comment_start_string=COMMENT_START_STRING,
778 comment_end_string=COMMENT_END_STRING,
779 line_statement_prefix=LINE_STATEMENT_PREFIX,
780 line_comment_prefix=LINE_COMMENT_PREFIX,
781 trim_blocks=TRIM_BLOCKS,
782 newline_sequence=NEWLINE_SEQUENCE,
788 env = get_spontaneous_environment(
789 block_start_string, block_end_string, variable_start_string,
790 variable_end_string, comment_start_string, comment_end_string,
791 line_statement_prefix, line_comment_prefix, trim_blocks,
792 newline_sequence, frozenset(extensions), optimized, undefined,
793 finalize, autoescape, None, 0, False, None)
794 return env.from_string(source, template_class=cls)
797 def from_code(cls, environment, code, globals, uptodate=None):
798 """Creates a template object from compiled code and the globals. This
799 is used by the loaders and environment to create a template object.
802 'environment': environment,
803 '__file__': code.co_filename
805 exec code in namespace
806 rv = cls._from_namespace(environment, namespace, globals)
807 rv._uptodate = uptodate
811 def from_module_dict(cls, environment, module_dict, globals):
812 """Creates a template object from a module. This is used by the
813 module loader to create a template object.
815 .. versionadded:: 2.4
817 return cls._from_namespace(environment, module_dict, globals)
820 def _from_namespace(cls, environment, namespace, globals):
821 t = object.__new__(cls)
822 t.environment = environment
824 t.name = namespace['name']
825 t.filename = namespace['__file__']
826 t.blocks = namespace['blocks']
828 # render function and module
829 t.root_render_func = namespace['root']
832 # debug and loader helpers
833 t._debug_info = namespace['debug_info']
836 # store the reference
837 namespace['environment'] = environment
838 namespace['__jinja_template__'] = t
842 def render(self, *args, **kwargs):
843 """This method accepts the same arguments as the `dict` constructor:
844 A dict, a dict subclass or some keyword arguments. If no arguments
845 are given the context will be empty. These two calls do the same::
847 template.render(knights='that say nih')
848 template.render({'knights': 'that say nih'})
850 This will return the rendered template as unicode string.
852 vars = dict(*args, **kwargs)
854 return concat(self.root_render_func(self.new_context(vars)))
856 exc_info = sys.exc_info()
857 return self.environment.handle_exception(exc_info, True)
859 def stream(self, *args, **kwargs):
860 """Works exactly like :meth:`generate` but returns a
861 :class:`TemplateStream`.
863 return TemplateStream(self.generate(*args, **kwargs))
865 def generate(self, *args, **kwargs):
866 """For very large templates it can be useful to not render the whole
867 template at once but evaluate each statement after another and yield
868 piece for piece. This method basically does exactly that and returns
869 a generator that yields one item after another as unicode strings.
871 It accepts the same arguments as :meth:`render`.
873 vars = dict(*args, **kwargs)
875 for event in self.root_render_func(self.new_context(vars)):
878 exc_info = sys.exc_info()
881 yield self.environment.handle_exception(exc_info, True)
883 def new_context(self, vars=None, shared=False, locals=None):
884 """Create a new :class:`Context` for this template. The vars
885 provided will be passed to the template. Per default the globals
886 are added to the context. If shared is set to `True` the data
887 is passed as it to the context without adding the globals.
889 `locals` can be a dict of local variables for internal usage.
891 return new_context(self.environment, self.name, self.blocks,
892 vars, shared, self.globals, locals)
894 def make_module(self, vars=None, shared=False, locals=None):
895 """This method works like the :attr:`module` attribute when called
896 without arguments but it will evaluate the template on every call
897 rather than caching it. It's also possible to provide
898 a dict which is then used as context. The arguments are the same
899 as for the :meth:`new_context` method.
901 return TemplateModule(self, self.new_context(vars, shared, locals))
905 """The template as module. This is used for imports in the
906 template runtime but is also useful if one wants to access
907 exported template variables from the Python layer:
909 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
910 >>> unicode(t.module)
915 if self._module is not None:
917 self._module = rv = self.make_module()
920 def get_corresponding_lineno(self, lineno):
921 """Return the source line number of a line number in the
922 generated bytecode as they are not in sync.
924 for template_line, code_line in reversed(self.debug_info):
925 if code_line <= lineno:
930 def is_up_to_date(self):
931 """If this variable is `False` there is a newer version available."""
932 if self._uptodate is None:
934 return self._uptodate()
937 def debug_info(self):
938 """The debug info mapping."""
939 return [tuple(map(int, x.split('='))) for x in
940 self._debug_info.split('&')]
943 if self.name is None:
944 name = 'memory:%x' % id(self)
946 name = repr(self.name)
947 return '<%s %s>' % (self.__class__.__name__, name)
950 class TemplateModule(object):
951 """Represents an imported template. All the exported names of the
952 template are available as attributes on this object. Additionally
953 converting it into an unicode- or bytestrings renders the contents.
956 def __init__(self, template, context):
957 self._body_stream = list(template.root_render_func(context))
958 self.__dict__.update(context.get_exported())
959 self.__name__ = template.name
962 return Markup(concat(self._body_stream))
965 return unicode(self).encode('utf-8')
967 # unicode goes after __str__ because we configured 2to3 to rename
968 # __unicode__ to __str__. because the 2to3 tree is not designed to
969 # remove nodes from it, we leave the above __str__ around and let
970 # it override at runtime.
971 def __unicode__(self):
972 return concat(self._body_stream)
975 if self.__name__ is None:
976 name = 'memory:%x' % id(self)
978 name = repr(self.__name__)
979 return '<%s %s>' % (self.__class__.__name__, name)
982 class TemplateExpression(object):
983 """The :meth:`jinja2.Environment.compile_expression` method returns an
984 instance of this object. It encapsulates the expression-like access
985 to the template with an expression it wraps.
988 def __init__(self, template, undefined_to_none):
989 self._template = template
990 self._undefined_to_none = undefined_to_none
992 def __call__(self, *args, **kwargs):
993 context = self._template.new_context(dict(*args, **kwargs))
994 consume(self._template.root_render_func(context))
995 rv = context.vars['result']
996 if self._undefined_to_none and isinstance(rv, Undefined):
1001 class TemplateStream(object):
1002 """A template stream works pretty much like an ordinary python generator
1003 but it can buffer multiple items to reduce the number of total iterations.
1004 Per default the output is unbuffered which means that for every unbuffered
1005 instruction in the template one unicode string is yielded.
1007 If buffering is enabled with a buffer size of 5, five items are combined
1008 into a new unicode string. This is mainly useful if you are streaming
1009 big templates to a client via WSGI which flushes after each iteration.
1012 def __init__(self, gen):
1014 self.disable_buffering()
1016 def dump(self, fp, encoding=None, errors='strict'):
1017 """Dump the complete stream into a file or file-like object.
1018 Per default unicode strings are written, if you want to encode
1019 before writing specifiy an `encoding`.
1023 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
1026 if isinstance(fp, basestring):
1030 if encoding is not None:
1031 iterable = (x.encode(encoding, errors) for x in self)
1034 if hasattr(fp, 'writelines'):
1035 fp.writelines(iterable)
1037 for item in iterable:
1043 def disable_buffering(self):
1044 """Disable the output buffering."""
1045 self._next = self._gen.next
1046 self.buffered = False
1048 def enable_buffering(self, size=5):
1049 """Enable buffering. Buffer `size` items before yielding them."""
1051 raise ValueError('buffer size too small')
1053 def generator(next):
1060 while c_size < size:
1065 except StopIteration:
1072 self.buffered = True
1073 self._next = generator(self._gen.next).next
1082 # hook in default template class. if anyone reads this comment: ignore that
1083 # it's possible to use custom templates ;-)
1084 Environment.template_class = Template