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.
12 from jinja2 import nodes
13 from jinja2.defaults import *
14 from jinja2.lexer import get_lexer, TokenStream
15 from jinja2.parser import Parser
16 from jinja2.optimizer import optimize
17 from jinja2.compiler import generate
18 from jinja2.runtime import Undefined, new_context
19 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \
21 from jinja2.utils import import_string, LRUCache, Markup, missing, \
22 concat, consume, internalcode, _encode_filename
25 # for direct template usage we have up to ten living environments
26 _spontaneous_environments = LRUCache(10)
28 # the function to create jinja traceback objects. This is dynamically
29 # imported on the first exception in the exception handler.
30 _make_traceback = None
33 def get_spontaneous_environment(*args):
34 """Return a new spontaneous environment. A spontaneous environment is an
35 unnamed and unaccessible (in theory) environment that is used for
36 templates generated from a string and not from the file system.
39 env = _spontaneous_environments.get(args)
41 return Environment(*args)
44 _spontaneous_environments[args] = env = Environment(*args)
49 def create_cache(size):
50 """Return the cache class for the given size."""
58 def copy_cache(cache):
59 """Create an empty copy of the given cache."""
62 elif type(cache) is dict:
64 return LRUCache(cache.capacity)
67 def load_extensions(environment, extensions):
68 """Load the extensions from the list and bind it to the environment.
69 Returns a dict of instanciated environments.
72 for extension in extensions:
73 if isinstance(extension, basestring):
74 extension = import_string(extension)
75 result[extension.identifier] = extension(environment)
79 def _environment_sanity_check(environment):
80 """Perform a sanity check on the environment."""
81 assert issubclass(environment.undefined, Undefined), 'undefined must ' \
82 'be a subclass of undefined because filters depend on it.'
83 assert environment.block_start_string != \
84 environment.variable_start_string != \
85 environment.comment_start_string, 'block, variable and comment ' \
86 'start strings must be different'
87 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
88 'newline_sequence set to unknown line ending string.'
92 class Environment(object):
93 r"""The core component of Jinja is the `Environment`. It contains
94 important shared variables like configuration, filters, tests,
95 globals and others. Instances of this class may be modified if
96 they are not shared and if no template was loaded so far.
97 Modifications on environments after the first template was loaded
98 will lead to surprising effects and undefined behavior.
100 Here the possible initialization parameters:
103 The string marking the begin of a block. Defaults to ``'{%'``.
106 The string marking the end of a block. Defaults to ``'%}'``.
108 `variable_start_string`
109 The string marking the begin of a print statement.
110 Defaults to ``'{{'``.
112 `variable_end_string`
113 The string marking the end of a print statement. Defaults to
116 `comment_start_string`
117 The string marking the begin of a comment. Defaults to ``'{#'``.
120 The string marking the end of a comment. Defaults to ``'#}'``.
122 `line_statement_prefix`
123 If given and a string, this will be used as prefix for line based
124 statements. See also :ref:`line-statements`.
126 `line_comment_prefix`
127 If given and a string, this will be used as prefix for line based
128 based comments. See also :ref:`line-statements`.
130 .. versionadded:: 2.2
133 If this is set to ``True`` the first newline after a block is
134 removed (block, not variable tag!). Defaults to `False`.
137 The sequence that starts a newline. Must be one of ``'\r'``,
138 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
139 useful default for Linux and OS X systems as well as web
143 List of Jinja extensions to use. This can either be import paths
144 as strings or extension classes. For more information have a
145 look at :ref:`the extensions documentation <jinja-extensions>`.
148 should the optimizer be enabled? Default is `True`.
151 :class:`Undefined` or a subclass of it that is used to represent
152 undefined values in the template.
155 A callable that can be used to process the result of a variable
156 expression before it is output. For example one can convert
157 `None` implicitly into an empty string here.
160 If set to true the XML/HTML autoescaping feature is enabled.
161 For more details about auto escaping see
162 :class:`~jinja2.utils.Markup`.
165 The template loader for this environment.
168 The size of the cache. Per default this is ``50`` which means
169 that if more than 50 templates are loaded the loader will clean
170 out the least recently used template. If the cache size is set to
171 ``0`` templates are recompiled all the time, if the cache size is
172 ``-1`` the cache will not be cleaned.
175 Some loaders load templates from locations where the template
176 sources may change (ie: file system or database). If
177 `auto_reload` is set to `True` (default) every time a template is
178 requested the loader checks if the source changed and if yes, it
179 will reload the template. For higher performance it's possible to
183 If set to a bytecode cache object, this object will provide a
184 cache for the internal Jinja bytecode so that templates don't
185 have to be parsed if they were not changed.
187 See :ref:`bytecode-cache` for more information.
190 #: if this environment is sandboxed. Modifying this variable won't make
191 #: the environment sandboxed though. For a real sandboxed environment
192 #: have a look at jinja2.sandbox
195 #: True if the environment is just an overlay
198 #: the environment this environment is linked to if it is an overlay
201 #: shared environments have this set to `True`. A shared environment
202 #: must not be modified
205 #: these are currently EXPERIMENTAL undocumented features.
206 exception_handler = None
207 exception_formatter = None
210 block_start_string=BLOCK_START_STRING,
211 block_end_string=BLOCK_END_STRING,
212 variable_start_string=VARIABLE_START_STRING,
213 variable_end_string=VARIABLE_END_STRING,
214 comment_start_string=COMMENT_START_STRING,
215 comment_end_string=COMMENT_END_STRING,
216 line_statement_prefix=LINE_STATEMENT_PREFIX,
217 line_comment_prefix=LINE_COMMENT_PREFIX,
218 trim_blocks=TRIM_BLOCKS,
219 newline_sequence=NEWLINE_SEQUENCE,
228 bytecode_cache=None):
229 # !!Important notice!!
230 # The constructor accepts quite a few arguments that should be
231 # passed by keyword rather than position. However it's important to
232 # not change the order of arguments because it's used at least
233 # internally in those cases:
234 # - spontaneus environments (i18n extension and Template)
236 # If parameter changes are required only add parameters at the end
237 # and don't change the arguments (or the defaults!) of the arguments
240 # lexer / parser information
241 self.block_start_string = block_start_string
242 self.block_end_string = block_end_string
243 self.variable_start_string = variable_start_string
244 self.variable_end_string = variable_end_string
245 self.comment_start_string = comment_start_string
246 self.comment_end_string = comment_end_string
247 self.line_statement_prefix = line_statement_prefix
248 self.line_comment_prefix = line_comment_prefix
249 self.trim_blocks = trim_blocks
250 self.newline_sequence = newline_sequence
252 # runtime information
253 self.undefined = undefined
254 self.optimized = optimized
255 self.finalize = finalize
256 self.autoescape = autoescape
259 self.filters = DEFAULT_FILTERS.copy()
260 self.tests = DEFAULT_TESTS.copy()
261 self.globals = DEFAULT_NAMESPACE.copy()
263 # set the loader provided
265 self.bytecode_cache = None
266 self.cache = create_cache(cache_size)
267 self.bytecode_cache = bytecode_cache
268 self.auto_reload = auto_reload
271 self.extensions = load_extensions(self, extensions)
273 _environment_sanity_check(self)
275 def extend(self, **attributes):
276 """Add the items to the instance of the environment if they do not exist
277 yet. This is used by :ref:`extensions <writing-extensions>` to register
278 callbacks and configuration values without breaking inheritance.
280 for key, value in attributes.iteritems():
281 if not hasattr(self, key):
282 setattr(self, key, value)
284 def overlay(self, block_start_string=missing, block_end_string=missing,
285 variable_start_string=missing, variable_end_string=missing,
286 comment_start_string=missing, comment_end_string=missing,
287 line_statement_prefix=missing, line_comment_prefix=missing,
288 trim_blocks=missing, extensions=missing, optimized=missing,
289 undefined=missing, finalize=missing, autoescape=missing,
290 loader=missing, cache_size=missing, auto_reload=missing,
291 bytecode_cache=missing):
292 """Create a new overlay environment that shares all the data with the
293 current environment except of cache and the overridden attributes.
294 Extensions cannot be removed for an overlayed environment. An overlayed
295 environment automatically gets all the extensions of the environment it
296 is linked to plus optional extra extensions.
298 Creating overlays should happen after the initial environment was set
299 up completely. Not all attributes are truly linked, some are just
300 copied over so modifications on the original environment may not shine
303 args = dict(locals())
304 del args['self'], args['cache_size'], args['extensions']
306 rv = object.__new__(self.__class__)
307 rv.__dict__.update(self.__dict__)
311 for key, value in args.iteritems():
312 if value is not missing:
313 setattr(rv, key, value)
315 if cache_size is not missing:
316 rv.cache = create_cache(cache_size)
318 rv.cache = copy_cache(self.cache)
321 for key, value in self.extensions.iteritems():
322 rv.extensions[key] = value.bind(rv)
323 if extensions is not missing:
324 rv.extensions.update(load_extensions(extensions))
326 return _environment_sanity_check(rv)
328 lexer = property(get_lexer, doc="The lexer for this environment.")
330 def getitem(self, obj, argument):
331 """Get an item or attribute of an object but prefer the item."""
334 except (TypeError, LookupError):
335 if isinstance(argument, basestring):
342 return getattr(obj, attr)
343 except AttributeError:
345 return self.undefined(obj=obj, name=argument)
347 def getattr(self, obj, attribute):
348 """Get an item or attribute of an object but prefer the attribute.
349 Unlike :meth:`getitem` the attribute *must* be a bytestring.
352 return getattr(obj, attribute)
353 except AttributeError:
356 return obj[attribute]
357 except (TypeError, LookupError, AttributeError):
358 return self.undefined(obj=obj, name=attribute)
361 def parse(self, source, name=None, filename=None):
362 """Parse the sourcecode and return the abstract syntax tree. This
363 tree of nodes is used by the compiler to convert the template into
364 executable source- or bytecode. This is useful for debugging or to
365 extract information from templates.
367 If you are :ref:`developing Jinja2 extensions <writing-extensions>`
368 this gives you a good overview of the node tree generated.
371 return self._parse(source, name, filename)
372 except TemplateSyntaxError:
373 exc_info = sys.exc_info()
374 self.handle_exception(exc_info, source_hint=source)
376 def _parse(self, source, name, filename):
377 """Internal parsing function used by `parse` and `compile`."""
378 return Parser(self, source, name, _encode_filename(filename)).parse()
380 def lex(self, source, name=None, filename=None):
381 """Lex the given sourcecode and return a generator that yields
382 tokens as tuples in the form ``(lineno, token_type, value)``.
383 This can be useful for :ref:`extension development <writing-extensions>`
384 and debugging templates.
386 This does not perform preprocessing. If you want the preprocessing
387 of the extensions to be applied you have to filter source through
388 the :meth:`preprocess` method.
390 source = unicode(source)
392 return self.lexer.tokeniter(source, name, filename)
393 except TemplateSyntaxError:
394 exc_info = sys.exc_info()
395 self.handle_exception(exc_info, source_hint=source)
397 def preprocess(self, source, name=None, filename=None):
398 """Preprocesses the source with all extensions. This is automatically
399 called for all parsing and compiling methods but *not* for :meth:`lex`
400 because there you usually only want the actual source tokenized.
402 return reduce(lambda s, e: e.preprocess(s, name, filename),
403 self.extensions.itervalues(), unicode(source))
405 def _tokenize(self, source, name, filename=None, state=None):
406 """Called by the parser to do the preprocessing and filtering
407 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
409 source = self.preprocess(source, name, filename)
410 stream = self.lexer.tokenize(source, name, filename, state)
411 for ext in self.extensions.itervalues():
412 stream = ext.filter_stream(stream)
413 if not isinstance(stream, TokenStream):
414 stream = TokenStream(stream, name, filename)
418 def compile(self, source, name=None, filename=None, raw=False):
419 """Compile a node or template source code. The `name` parameter is
420 the load name of the template after it was joined using
421 :meth:`join_path` if necessary, not the filename on the file system.
422 the `filename` parameter is the estimated filename of the template on
423 the file system. If the template came from a database or memory this
426 The return value of this method is a python code object. If the `raw`
427 parameter is `True` the return value will be a string with python
428 code equivalent to the bytecode returned otherwise. This method is
429 mainly used internally.
433 if isinstance(source, basestring):
435 source = self._parse(source, name, filename)
437 source = optimize(source, self)
438 source = generate(source, self, name, filename)
442 filename = '<template>'
444 filename = _encode_filename(filename)
445 return compile(source, filename, 'exec')
446 except TemplateSyntaxError:
447 exc_info = sys.exc_info()
448 self.handle_exception(exc_info, source_hint=source)
450 def compile_expression(self, source, undefined_to_none=True):
451 """A handy helper method that returns a callable that accepts keyword
452 arguments that appear as variables in the expression. If called it
453 returns the result of the expression.
455 This is useful if applications want to use the same rules as Jinja
456 in template "configuration files" or similar situations.
460 >>> env = Environment()
461 >>> expr = env.compile_expression('foo == 42')
467 Per default the return value is converted to `None` if the
468 expression returns an undefined value. This can be changed
469 by setting `undefined_to_none` to `False`.
471 >>> env.compile_expression('var')() is None
473 >>> env.compile_expression('var', undefined_to_none=False)()
476 .. versionadded:: 2.1
478 parser = Parser(self, source, state='variable')
481 expr = parser.parse_expression()
482 if not parser.stream.eos:
483 raise TemplateSyntaxError('chunk after expression',
484 parser.stream.current.lineno,
486 except TemplateSyntaxError:
487 exc_info = sys.exc_info()
488 if exc_info is not None:
489 self.handle_exception(exc_info, source_hint=source)
490 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
491 template = self.from_string(nodes.Template(body, lineno=1))
492 return TemplateExpression(template, undefined_to_none)
494 def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
495 """Exception handling helper. This is used internally to either raise
496 rewritten exceptions or return a rendered traceback for the template.
498 global _make_traceback
500 exc_info = sys.exc_info()
502 # the debugging module is imported when it's used for the first time.
503 # we're doing a lot of stuff there and for applications that do not
504 # get any exceptions in template rendering there is no need to load
506 if _make_traceback is None:
507 from jinja2.debug import make_traceback as _make_traceback
508 traceback = _make_traceback(exc_info, source_hint)
509 if rendered and self.exception_formatter is not None:
510 return self.exception_formatter(traceback)
511 if self.exception_handler is not None:
512 self.exception_handler(traceback)
513 exc_type, exc_value, tb = traceback.standard_exc_info
514 raise exc_type, exc_value, tb
516 def join_path(self, template, parent):
517 """Join a template with the parent. By default all the lookups are
518 relative to the loader root so this method returns the `template`
519 parameter unchanged, but if the paths should be relative to the
520 parent template, this function can be used to calculate the real
523 Subclasses may override this method and implement template path
529 def _load_template(self, name, globals):
530 if self.loader is None:
531 raise TypeError('no loader for this environment specified')
532 if self.cache is not None:
533 template = self.cache.get(name)
534 if template is not None and (not self.auto_reload or \
535 template.is_up_to_date):
537 template = self.loader.load(self, name, globals)
538 if self.cache is not None:
539 self.cache[name] = template
543 def get_template(self, name, parent=None, globals=None):
544 """Load a template from the loader. If a loader is configured this
545 method ask the loader for the template and returns a :class:`Template`.
546 If the `parent` parameter is not `None`, :meth:`join_path` is called
547 to get the real template name before loading.
549 The `globals` parameter can be used to provide template wide globals.
550 These variables are available in the context at render time.
552 If the template does not exist a :exc:`TemplateNotFound` exception is
555 if parent is not None:
556 name = self.join_path(name, parent)
557 return self._load_template(name, self.make_globals(globals))
560 def select_template(self, names, parent=None, globals=None):
561 """Works like :meth:`get_template` but tries a number of templates
562 before it fails. If it cannot find any of the templates, it will
563 raise a :exc:`TemplatesNotFound` exception.
565 .. versionadded:: 2.3
568 raise TemplatesNotFound(message=u'Tried to select from an empty list '
570 globals = self.make_globals(globals)
572 if parent is not None:
573 name = self.join_path(name, parent)
575 return self._load_template(name, globals)
576 except TemplateNotFound:
578 raise TemplatesNotFound(names)
581 def get_or_select_template(self, template_name_or_list,
582 parent=None, globals=None):
584 Does a typecheck and dispatches to :meth:`select_template` if an
585 iterable of template names is given, otherwise to :meth:`get_template`.
587 .. versionadded:: 2.3
589 if isinstance(template_name_or_list, basestring):
590 return self.get_template(template_name_or_list, parent, globals)
591 return self.select_template(template_name_or_list, parent, globals)
593 def from_string(self, source, globals=None, template_class=None):
594 """Load a template from a string. This parses the source given and
595 returns a :class:`Template` object.
597 globals = self.make_globals(globals)
598 cls = template_class or self.template_class
599 return cls.from_code(self, self.compile(source), globals, None)
601 def make_globals(self, d):
602 """Return a dict for the globals."""
605 return dict(self.globals, **d)
608 class Template(object):
609 """The central template object. This class represents a compiled template
610 and is used to evaluate it.
612 Normally the template object is generated from an :class:`Environment` but
613 it also has a constructor that makes it possible to create a template
614 instance directly using the constructor. It takes the same arguments as
615 the environment constructor but it's not possible to specify a loader.
617 Every template object has a few methods and members that are guaranteed
618 to exist. However it's important that a template object should be
619 considered immutable. Modifications on the object are not supported.
621 Template objects created from the constructor rather than an environment
622 do have an `environment` attribute that points to a temporary environment
623 that is probably shared with other templates created with the constructor
624 and compatible settings.
626 >>> template = Template('Hello {{ name }}!')
627 >>> template.render(name='John Doe')
630 >>> stream = template.stream(name='John Doe')
634 Traceback (most recent call last):
639 def __new__(cls, source,
640 block_start_string=BLOCK_START_STRING,
641 block_end_string=BLOCK_END_STRING,
642 variable_start_string=VARIABLE_START_STRING,
643 variable_end_string=VARIABLE_END_STRING,
644 comment_start_string=COMMENT_START_STRING,
645 comment_end_string=COMMENT_END_STRING,
646 line_statement_prefix=LINE_STATEMENT_PREFIX,
647 line_comment_prefix=LINE_COMMENT_PREFIX,
648 trim_blocks=TRIM_BLOCKS,
649 newline_sequence=NEWLINE_SEQUENCE,
655 env = get_spontaneous_environment(
656 block_start_string, block_end_string, variable_start_string,
657 variable_end_string, comment_start_string, comment_end_string,
658 line_statement_prefix, line_comment_prefix, trim_blocks,
659 newline_sequence, frozenset(extensions), optimized, undefined,
660 finalize, autoescape, None, 0, False, None)
661 return env.from_string(source, template_class=cls)
664 def from_code(cls, environment, code, globals, uptodate=None):
665 """Creates a template object from compiled code and the globals. This
666 is used by the loaders and environment to create a template object.
668 t = object.__new__(cls)
670 'environment': environment,
671 '__jinja_template__': t
673 exec code in namespace
674 t.environment = environment
676 t.name = namespace['name']
677 t.filename = code.co_filename
678 t.blocks = namespace['blocks']
680 # render function and module
681 t.root_render_func = namespace['root']
684 # debug and loader helpers
685 t._debug_info = namespace['debug_info']
686 t._uptodate = uptodate
690 def render(self, *args, **kwargs):
691 """This method accepts the same arguments as the `dict` constructor:
692 A dict, a dict subclass or some keyword arguments. If no arguments
693 are given the context will be empty. These two calls do the same::
695 template.render(knights='that say nih')
696 template.render({'knights': 'that say nih'})
698 This will return the rendered template as unicode string.
700 vars = dict(*args, **kwargs)
702 return concat(self.root_render_func(self.new_context(vars)))
704 exc_info = sys.exc_info()
705 return self.environment.handle_exception(exc_info, True)
707 def stream(self, *args, **kwargs):
708 """Works exactly like :meth:`generate` but returns a
709 :class:`TemplateStream`.
711 return TemplateStream(self.generate(*args, **kwargs))
713 def generate(self, *args, **kwargs):
714 """For very large templates it can be useful to not render the whole
715 template at once but evaluate each statement after another and yield
716 piece for piece. This method basically does exactly that and returns
717 a generator that yields one item after another as unicode strings.
719 It accepts the same arguments as :meth:`render`.
721 vars = dict(*args, **kwargs)
723 for event in self.root_render_func(self.new_context(vars)):
726 exc_info = sys.exc_info()
729 yield self.environment.handle_exception(exc_info, True)
731 def new_context(self, vars=None, shared=False, locals=None):
732 """Create a new :class:`Context` for this template. The vars
733 provided will be passed to the template. Per default the globals
734 are added to the context. If shared is set to `True` the data
735 is passed as it to the context without adding the globals.
737 `locals` can be a dict of local variables for internal usage.
739 return new_context(self.environment, self.name, self.blocks,
740 vars, shared, self.globals, locals)
742 def make_module(self, vars=None, shared=False, locals=None):
743 """This method works like the :attr:`module` attribute when called
744 without arguments but it will evaluate the template on every call
745 rather than caching it. It's also possible to provide
746 a dict which is then used as context. The arguments are the same
747 as for the :meth:`new_context` method.
749 return TemplateModule(self, self.new_context(vars, shared, locals))
753 """The template as module. This is used for imports in the
754 template runtime but is also useful if one wants to access
755 exported template variables from the Python layer:
757 >>> t = Template('{% macro foo() %}42{% endmacro %}23')
758 >>> unicode(t.module)
763 if self._module is not None:
765 self._module = rv = self.make_module()
768 def get_corresponding_lineno(self, lineno):
769 """Return the source line number of a line number in the
770 generated bytecode as they are not in sync.
772 for template_line, code_line in reversed(self.debug_info):
773 if code_line <= lineno:
778 def is_up_to_date(self):
779 """If this variable is `False` there is a newer version available."""
780 if self._uptodate is None:
782 return self._uptodate()
785 def debug_info(self):
786 """The debug info mapping."""
787 return [tuple(map(int, x.split('='))) for x in
788 self._debug_info.split('&')]
791 if self.name is None:
792 name = 'memory:%x' % id(self)
794 name = repr(self.name)
795 return '<%s %s>' % (self.__class__.__name__, name)
798 class TemplateModule(object):
799 """Represents an imported template. All the exported names of the
800 template are available as attributes on this object. Additionally
801 converting it into an unicode- or bytestrings renders the contents.
804 def __init__(self, template, context):
805 self._body_stream = list(template.root_render_func(context))
806 self.__dict__.update(context.get_exported())
807 self.__name__ = template.name
810 return Markup(concat(self._body_stream))
813 return unicode(self).encode('utf-8')
815 # unicode goes after __str__ because we configured 2to3 to rename
816 # __unicode__ to __str__. because the 2to3 tree is not designed to
817 # remove nodes from it, we leave the above __str__ around and let
818 # it override at runtime.
819 def __unicode__(self):
820 return concat(self._body_stream)
823 if self.__name__ is None:
824 name = 'memory:%x' % id(self)
826 name = repr(self.__name__)
827 return '<%s %s>' % (self.__class__.__name__, name)
830 class TemplateExpression(object):
831 """The :meth:`jinja2.Environment.compile_expression` method returns an
832 instance of this object. It encapsulates the expression-like access
833 to the template with an expression it wraps.
836 def __init__(self, template, undefined_to_none):
837 self._template = template
838 self._undefined_to_none = undefined_to_none
840 def __call__(self, *args, **kwargs):
841 context = self._template.new_context(dict(*args, **kwargs))
842 consume(self._template.root_render_func(context))
843 rv = context.vars['result']
844 if self._undefined_to_none and isinstance(rv, Undefined):
849 class TemplateStream(object):
850 """A template stream works pretty much like an ordinary python generator
851 but it can buffer multiple items to reduce the number of total iterations.
852 Per default the output is unbuffered which means that for every unbuffered
853 instruction in the template one unicode string is yielded.
855 If buffering is enabled with a buffer size of 5, five items are combined
856 into a new unicode string. This is mainly useful if you are streaming
857 big templates to a client via WSGI which flushes after each iteration.
860 def __init__(self, gen):
862 self.disable_buffering()
864 def dump(self, fp, encoding=None, errors='strict'):
865 """Dump the complete stream into a file or file-like object.
866 Per default unicode strings are written, if you want to encode
867 before writing specifiy an `encoding`.
871 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
874 if isinstance(fp, basestring):
878 if encoding is not None:
879 iterable = (x.encode(encoding, errors) for x in self)
882 if hasattr(fp, 'writelines'):
883 fp.writelines(iterable)
885 for item in iterable:
891 def disable_buffering(self):
892 """Disable the output buffering."""
893 self._next = self._gen.next
894 self.buffered = False
896 def enable_buffering(self, size=5):
897 """Enable buffering. Buffer `size` items before yielding them."""
899 raise ValueError('buffer size too small')
913 except StopIteration:
921 self._next = generator(self._gen.next).next
930 # hook in default template class. if anyone reads this comment: ignore that
931 # it's possible to use custom templates ;-)
932 Environment.template_class = Template