babel extraction can now properly extract newstyle gettext calls.
[jinja2.git] / jinja2 / environment.py
1 # -*- coding: utf-8 -*-
2 """
3     jinja2.environment
4     ~~~~~~~~~~~~~~~~~~
5
6     Provides a class that holds runtime and parsing time options.
7
8     :copyright: (c) 2010 by the Jinja Team.
9     :license: BSD, see LICENSE for more details.
10 """
11 import os
12 import sys
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, \
21      TemplatesNotFound
22 from jinja2.utils import import_string, LRUCache, Markup, missing, \
23      concat, consume, internalcode, _encode_filename
24
25
26 # for direct template usage we have up to ten living environments
27 _spontaneous_environments = LRUCache(10)
28
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
32
33
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.
38     """
39     try:
40         env = _spontaneous_environments.get(args)
41     except TypeError:
42         return Environment(*args)
43     if env is not None:
44         return env
45     _spontaneous_environments[args] = env = Environment(*args)
46     env.shared = True
47     return env
48
49
50 def create_cache(size):
51     """Return the cache class for the given size."""
52     if size == 0:
53         return None
54     if size < 0:
55         return {}
56     return LRUCache(size)
57
58
59 def copy_cache(cache):
60     """Create an empty copy of the given cache."""
61     if cache is None:
62         return None
63     elif type(cache) is dict:
64         return {}
65     return LRUCache(cache.capacity)
66
67
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.
71     """
72     result = {}
73     for extension in extensions:
74         if isinstance(extension, basestring):
75             extension = import_string(extension)
76         result[extension.identifier] = extension(environment)
77     return result
78
79
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.'
90     return environment
91
92
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.
100
101     Here the possible initialization parameters:
102
103         `block_start_string`
104             The string marking the begin of a block.  Defaults to ``'{%'``.
105
106         `block_end_string`
107             The string marking the end of a block.  Defaults to ``'%}'``.
108
109         `variable_start_string`
110             The string marking the begin of a print statement.
111             Defaults to ``'{{'``.
112
113         `variable_end_string`
114             The string marking the end of a print statement.  Defaults to
115             ``'}}'``.
116
117         `comment_start_string`
118             The string marking the begin of a comment.  Defaults to ``'{#'``.
119
120         `comment_end_string`
121             The string marking the end of a comment.  Defaults to ``'#}'``.
122
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`.
126
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`.
130
131             .. versionadded:: 2.2
132
133         `trim_blocks`
134             If this is set to ``True`` the first newline after a block is
135             removed (block, not variable tag!).  Defaults to `False`.
136
137         `newline_sequence`
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
141             applications.
142
143         `extensions`
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>`.
147
148         `optimized`
149             should the optimizer be enabled?  Default is `True`.
150
151         `undefined`
152             :class:`Undefined` or a subclass of it that is used to represent
153             undefined values in the template.
154
155         `finalize`
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.
159
160         `autoescape`
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`.  As of Jinja 2.4 this can also
164             be a callable that is passed the template name and has to
165             return `True` or `False` depending on autoescape should be
166             enabled by default.
167
168             .. versionchanged:: 2.4
169                `autoescape` can now be a function
170
171         `loader`
172             The template loader for this environment.
173
174         `cache_size`
175             The size of the cache.  Per default this is ``50`` which means
176             that if more than 50 templates are loaded the loader will clean
177             out the least recently used template.  If the cache size is set to
178             ``0`` templates are recompiled all the time, if the cache size is
179             ``-1`` the cache will not be cleaned.
180
181         `auto_reload`
182             Some loaders load templates from locations where the template
183             sources may change (ie: file system or database).  If
184             `auto_reload` is set to `True` (default) every time a template is
185             requested the loader checks if the source changed and if yes, it
186             will reload the template.  For higher performance it's possible to
187             disable that.
188
189         `bytecode_cache`
190             If set to a bytecode cache object, this object will provide a
191             cache for the internal Jinja bytecode so that templates don't
192             have to be parsed if they were not changed.
193
194             See :ref:`bytecode-cache` for more information.
195     """
196
197     #: if this environment is sandboxed.  Modifying this variable won't make
198     #: the environment sandboxed though.  For a real sandboxed environment
199     #: have a look at jinja2.sandbox
200     sandboxed = False
201
202     #: True if the environment is just an overlay
203     overlayed = False
204
205     #: the environment this environment is linked to if it is an overlay
206     linked_to = None
207
208     #: shared environments have this set to `True`.  A shared environment
209     #: must not be modified
210     shared = False
211
212     #: these are currently EXPERIMENTAL undocumented features.
213     exception_handler = None
214     exception_formatter = None
215
216     def __init__(self,
217                  block_start_string=BLOCK_START_STRING,
218                  block_end_string=BLOCK_END_STRING,
219                  variable_start_string=VARIABLE_START_STRING,
220                  variable_end_string=VARIABLE_END_STRING,
221                  comment_start_string=COMMENT_START_STRING,
222                  comment_end_string=COMMENT_END_STRING,
223                  line_statement_prefix=LINE_STATEMENT_PREFIX,
224                  line_comment_prefix=LINE_COMMENT_PREFIX,
225                  trim_blocks=TRIM_BLOCKS,
226                  newline_sequence=NEWLINE_SEQUENCE,
227                  extensions=(),
228                  optimized=True,
229                  undefined=Undefined,
230                  finalize=None,
231                  autoescape=False,
232                  loader=None,
233                  cache_size=50,
234                  auto_reload=True,
235                  bytecode_cache=None):
236         # !!Important notice!!
237         #   The constructor accepts quite a few arguments that should be
238         #   passed by keyword rather than position.  However it's important to
239         #   not change the order of arguments because it's used at least
240         #   internally in those cases:
241         #       -   spontaneus environments (i18n extension and Template)
242         #       -   unittests
243         #   If parameter changes are required only add parameters at the end
244         #   and don't change the arguments (or the defaults!) of the arguments
245         #   existing already.
246
247         # lexer / parser information
248         self.block_start_string = block_start_string
249         self.block_end_string = block_end_string
250         self.variable_start_string = variable_start_string
251         self.variable_end_string = variable_end_string
252         self.comment_start_string = comment_start_string
253         self.comment_end_string = comment_end_string
254         self.line_statement_prefix = line_statement_prefix
255         self.line_comment_prefix = line_comment_prefix
256         self.trim_blocks = trim_blocks
257         self.newline_sequence = newline_sequence
258
259         # runtime information
260         self.undefined = undefined
261         self.optimized = optimized
262         self.finalize = finalize
263         self.autoescape = autoescape
264
265         # defaults
266         self.filters = DEFAULT_FILTERS.copy()
267         self.tests = DEFAULT_TESTS.copy()
268         self.globals = DEFAULT_NAMESPACE.copy()
269
270         # set the loader provided
271         self.loader = loader
272         self.bytecode_cache = None
273         self.cache = create_cache(cache_size)
274         self.bytecode_cache = bytecode_cache
275         self.auto_reload = auto_reload
276
277         # load extensions
278         self.extensions = load_extensions(self, extensions)
279
280         _environment_sanity_check(self)
281
282     def add_extension(self, extension):
283         """Adds an extension after the environment was created.
284
285         .. versionadded:: 2.5
286         """
287         self.extensions.update(load_extensions(self, [extension]))
288
289     def extend(self, **attributes):
290         """Add the items to the instance of the environment if they do not exist
291         yet.  This is used by :ref:`extensions <writing-extensions>` to register
292         callbacks and configuration values without breaking inheritance.
293         """
294         for key, value in attributes.iteritems():
295             if not hasattr(self, key):
296                 setattr(self, key, value)
297
298     def overlay(self, block_start_string=missing, block_end_string=missing,
299                 variable_start_string=missing, variable_end_string=missing,
300                 comment_start_string=missing, comment_end_string=missing,
301                 line_statement_prefix=missing, line_comment_prefix=missing,
302                 trim_blocks=missing, extensions=missing, optimized=missing,
303                 undefined=missing, finalize=missing, autoescape=missing,
304                 loader=missing, cache_size=missing, auto_reload=missing,
305                 bytecode_cache=missing):
306         """Create a new overlay environment that shares all the data with the
307         current environment except of cache and the overridden attributes.
308         Extensions cannot be removed for an overlayed environment.  An overlayed
309         environment automatically gets all the extensions of the environment it
310         is linked to plus optional extra extensions.
311
312         Creating overlays should happen after the initial environment was set
313         up completely.  Not all attributes are truly linked, some are just
314         copied over so modifications on the original environment may not shine
315         through.
316         """
317         args = dict(locals())
318         del args['self'], args['cache_size'], args['extensions']
319
320         rv = object.__new__(self.__class__)
321         rv.__dict__.update(self.__dict__)
322         rv.overlayed = True
323         rv.linked_to = self
324
325         for key, value in args.iteritems():
326             if value is not missing:
327                 setattr(rv, key, value)
328
329         if cache_size is not missing:
330             rv.cache = create_cache(cache_size)
331         else:
332             rv.cache = copy_cache(self.cache)
333
334         rv.extensions = {}
335         for key, value in self.extensions.iteritems():
336             rv.extensions[key] = value.bind(rv)
337         if extensions is not missing:
338             rv.extensions.update(load_extensions(extensions))
339
340         return _environment_sanity_check(rv)
341
342     lexer = property(get_lexer, doc="The lexer for this environment.")
343
344     def iter_extensions(self):
345         """Iterates over the extensions by priority."""
346         return iter(sorted(self.extensions.values(),
347                            key=lambda x: x.priority))
348
349     def getitem(self, obj, argument):
350         """Get an item or attribute of an object but prefer the item."""
351         try:
352             return obj[argument]
353         except (TypeError, LookupError):
354             if isinstance(argument, basestring):
355                 try:
356                     attr = str(argument)
357                 except:
358                     pass
359                 else:
360                     try:
361                         return getattr(obj, attr)
362                     except AttributeError:
363                         pass
364             return self.undefined(obj=obj, name=argument)
365
366     def getattr(self, obj, attribute):
367         """Get an item or attribute of an object but prefer the attribute.
368         Unlike :meth:`getitem` the attribute *must* be a bytestring.
369         """
370         try:
371             return getattr(obj, attribute)
372         except AttributeError:
373             pass
374         try:
375             return obj[attribute]
376         except (TypeError, LookupError, AttributeError):
377             return self.undefined(obj=obj, name=attribute)
378
379     @internalcode
380     def parse(self, source, name=None, filename=None):
381         """Parse the sourcecode and return the abstract syntax tree.  This
382         tree of nodes is used by the compiler to convert the template into
383         executable source- or bytecode.  This is useful for debugging or to
384         extract information from templates.
385
386         If you are :ref:`developing Jinja2 extensions <writing-extensions>`
387         this gives you a good overview of the node tree generated.
388         """
389         try:
390             return self._parse(source, name, filename)
391         except TemplateSyntaxError:
392             exc_info = sys.exc_info()
393         self.handle_exception(exc_info, source_hint=source)
394
395     def _parse(self, source, name, filename):
396         """Internal parsing function used by `parse` and `compile`."""
397         return Parser(self, source, name, _encode_filename(filename)).parse()
398
399     def lex(self, source, name=None, filename=None):
400         """Lex the given sourcecode and return a generator that yields
401         tokens as tuples in the form ``(lineno, token_type, value)``.
402         This can be useful for :ref:`extension development <writing-extensions>`
403         and debugging templates.
404
405         This does not perform preprocessing.  If you want the preprocessing
406         of the extensions to be applied you have to filter source through
407         the :meth:`preprocess` method.
408         """
409         source = unicode(source)
410         try:
411             return self.lexer.tokeniter(source, name, filename)
412         except TemplateSyntaxError:
413             exc_info = sys.exc_info()
414         self.handle_exception(exc_info, source_hint=source)
415
416     def preprocess(self, source, name=None, filename=None):
417         """Preprocesses the source with all extensions.  This is automatically
418         called for all parsing and compiling methods but *not* for :meth:`lex`
419         because there you usually only want the actual source tokenized.
420         """
421         return reduce(lambda s, e: e.preprocess(s, name, filename),
422                       self.iter_extensions(), unicode(source))
423
424     def _tokenize(self, source, name, filename=None, state=None):
425         """Called by the parser to do the preprocessing and filtering
426         for all the extensions.  Returns a :class:`~jinja2.lexer.TokenStream`.
427         """
428         source = self.preprocess(source, name, filename)
429         stream = self.lexer.tokenize(source, name, filename, state)
430         for ext in self.iter_extensions():
431             stream = ext.filter_stream(stream)
432             if not isinstance(stream, TokenStream):
433                 stream = TokenStream(stream, name, filename)
434         return stream
435
436     def _generate(self, source, name, filename, defer_init=False):
437         """Internal hook that can be overriden to hook a different generate
438         method in.
439
440         .. versionadded:: 2.5
441         """
442         return generate(source, self, name, filename, defer_init=defer_init)
443
444     def _compile(self, source, filename):
445         """Internal hook that can be overriden to hook a different compile
446         method in.
447
448         .. versionadded:: 2.5
449         """
450         return compile(source, filename, 'exec')
451
452     @internalcode
453     def compile(self, source, name=None, filename=None, raw=False,
454                 defer_init=False):
455         """Compile a node or template source code.  The `name` parameter is
456         the load name of the template after it was joined using
457         :meth:`join_path` if necessary, not the filename on the file system.
458         the `filename` parameter is the estimated filename of the template on
459         the file system.  If the template came from a database or memory this
460         can be omitted.
461
462         The return value of this method is a python code object.  If the `raw`
463         parameter is `True` the return value will be a string with python
464         code equivalent to the bytecode returned otherwise.  This method is
465         mainly used internally.
466
467         `defer_init` is use internally to aid the module code generator.  This
468         causes the generated code to be able to import without the global
469         environment variable to be set.
470
471         .. versionadded:: 2.4
472            `defer_init` parameter added.
473         """
474         source_hint = None
475         try:
476             if isinstance(source, basestring):
477                 source_hint = source
478                 source = self._parse(source, name, filename)
479             if self.optimized:
480                 source = optimize(source, self)
481             source = self._generate(source, name, filename,
482                                     defer_init=defer_init)
483             if raw:
484                 return source
485             if filename is None:
486                 filename = '<template>'
487             else:
488                 filename = _encode_filename(filename)
489             return self._compile(source, filename)
490         except TemplateSyntaxError:
491             exc_info = sys.exc_info()
492         self.handle_exception(exc_info, source_hint=source)
493
494     def compile_expression(self, source, undefined_to_none=True):
495         """A handy helper method that returns a callable that accepts keyword
496         arguments that appear as variables in the expression.  If called it
497         returns the result of the expression.
498
499         This is useful if applications want to use the same rules as Jinja
500         in template "configuration files" or similar situations.
501
502         Example usage:
503
504         >>> env = Environment()
505         >>> expr = env.compile_expression('foo == 42')
506         >>> expr(foo=23)
507         False
508         >>> expr(foo=42)
509         True
510
511         Per default the return value is converted to `None` if the
512         expression returns an undefined value.  This can be changed
513         by setting `undefined_to_none` to `False`.
514
515         >>> env.compile_expression('var')() is None
516         True
517         >>> env.compile_expression('var', undefined_to_none=False)()
518         Undefined
519
520         .. versionadded:: 2.1
521         """
522         parser = Parser(self, source, state='variable')
523         exc_info = None
524         try:
525             expr = parser.parse_expression()
526             if not parser.stream.eos:
527                 raise TemplateSyntaxError('chunk after expression',
528                                           parser.stream.current.lineno,
529                                           None, None)
530             expr.set_environment(self)
531         except TemplateSyntaxError:
532             exc_info = sys.exc_info()
533         if exc_info is not None:
534             self.handle_exception(exc_info, source_hint=source)
535         body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
536         template = self.from_string(nodes.Template(body, lineno=1))
537         return TemplateExpression(template, undefined_to_none)
538
539     def compile_templates(self, target, extensions=None, filter_func=None,
540                           zip='deflated', log_function=None,
541                           ignore_errors=True, py_compile=False):
542         """Compiles all the templates the loader can find, compiles them
543         and stores them in `target`.  If `zip` is `None`, instead of in a
544         zipfile, the templates will be will be stored in a directory.
545         By default a deflate zip algorithm is used, to switch to
546         the stored algorithm, `zip` can be set to ``'stored'``.
547
548         `extensions` and `filter_func` are passed to :meth:`list_templates`.
549         Each template returned will be compiled to the target folder or
550         zipfile.
551
552         By default template compilation errors are ignored.  In case a
553         log function is provided, errors are logged.  If you want template
554         syntax errors to abort the compilation you can set `ignore_errors`
555         to `False` and you will get an exception on syntax errors.
556
557         If `py_compile` is set to `True` .pyc files will be written to the
558         target instead of standard .py files.
559
560         .. versionadded:: 2.4
561         """
562         from jinja2.loaders import ModuleLoader
563
564         if log_function is None:
565             log_function = lambda x: None
566
567         if py_compile:
568             import imp, struct, marshal
569             py_header = imp.get_magic() + \
570                 u'\xff\xff\xff\xff'.encode('iso-8859-15')
571
572         def write_file(filename, data, mode):
573             if zip:
574                 info = ZipInfo(filename)
575                 info.external_attr = 0755 << 16L
576                 zip_file.writestr(info, data)
577             else:
578                 f = open(os.path.join(target, filename), mode)
579                 try:
580                     f.write(data)
581                 finally:
582                     f.close()
583
584         if zip is not None:
585             from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
586             zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED,
587                                                  stored=ZIP_STORED)[zip])
588             log_function('Compiling into Zip archive "%s"' % target)
589         else:
590             if not os.path.isdir(target):
591                 os.makedirs(target)
592             log_function('Compiling into folder "%s"' % target)
593
594         try:
595             for name in self.list_templates(extensions, filter_func):
596                 source, filename, _ = self.loader.get_source(self, name)
597                 try:
598                     code = self.compile(source, name, filename, True, True)
599                 except TemplateSyntaxError, e:
600                     if not ignore_errors:
601                         raise
602                     log_function('Could not compile "%s": %s' % (name, e))
603                     continue
604
605                 filename = ModuleLoader.get_module_filename(name)
606
607                 if py_compile:
608                     c = self._compile(code, _encode_filename(filename))
609                     write_file(filename + 'c', py_header +
610                                marshal.dumps(c), 'wb')
611                     log_function('Byte-compiled "%s" as %s' %
612                                  (name, filename + 'c'))
613                 else:
614                     write_file(filename, code, 'w')
615                     log_function('Compiled "%s" as %s' % (name, filename))
616         finally:
617             if zip:
618                 zip_file.close()
619
620         log_function('Finished compiling templates')
621
622     def list_templates(self, extensions=None, filter_func=None):
623         """Returns a list of templates for this environment.  This requires
624         that the loader supports the loader's
625         :meth:`~BaseLoader.list_templates` method.
626
627         If there are other files in the template folder besides the
628         actual templates, the returned list can be filtered.  There are two
629         ways: either `extensions` is set to a list of file extensions for
630         templates, or a `filter_func` can be provided which is a callable that
631         is passed a template name and should return `True` if it should end up
632         in the result list.
633
634         If the loader does not support that, a :exc:`TypeError` is raised.
635         """
636         x = self.loader.list_templates()
637         if extensions is not None:
638             if filter_func is not None:
639                 raise TypeError('either extensions or filter_func '
640                                 'can be passed, but not both')
641             filter_func = lambda x: '.' in x and \
642                                     x.rsplit('.', 1)[1] in extensions
643         if filter_func is not None:
644             x = filter(filter_func, x)
645         return x
646
647     def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
648         """Exception handling helper.  This is used internally to either raise
649         rewritten exceptions or return a rendered traceback for the template.
650         """
651         global _make_traceback
652         if exc_info is None:
653             exc_info = sys.exc_info()
654
655         # the debugging module is imported when it's used for the first time.
656         # we're doing a lot of stuff there and for applications that do not
657         # get any exceptions in template rendering there is no need to load
658         # all of that.
659         if _make_traceback is None:
660             from jinja2.debug import make_traceback as _make_traceback
661         traceback = _make_traceback(exc_info, source_hint)
662         if rendered and self.exception_formatter is not None:
663             return self.exception_formatter(traceback)
664         if self.exception_handler is not None:
665             self.exception_handler(traceback)
666         exc_type, exc_value, tb = traceback.standard_exc_info
667         raise exc_type, exc_value, tb
668
669     def join_path(self, template, parent):
670         """Join a template with the parent.  By default all the lookups are
671         relative to the loader root so this method returns the `template`
672         parameter unchanged, but if the paths should be relative to the
673         parent template, this function can be used to calculate the real
674         template name.
675
676         Subclasses may override this method and implement template path
677         joining here.
678         """
679         return template
680
681     @internalcode
682     def _load_template(self, name, globals):
683         if self.loader is None:
684             raise TypeError('no loader for this environment specified')
685         if self.cache is not None:
686             template = self.cache.get(name)
687             if template is not None and (not self.auto_reload or \
688                                          template.is_up_to_date):
689                 return template
690         template = self.loader.load(self, name, globals)
691         if self.cache is not None:
692             self.cache[name] = template
693         return template
694
695     @internalcode
696     def get_template(self, name, parent=None, globals=None):
697         """Load a template from the loader.  If a loader is configured this
698         method ask the loader for the template and returns a :class:`Template`.
699         If the `parent` parameter is not `None`, :meth:`join_path` is called
700         to get the real template name before loading.
701
702         The `globals` parameter can be used to provide template wide globals.
703         These variables are available in the context at render time.
704
705         If the template does not exist a :exc:`TemplateNotFound` exception is
706         raised.
707
708         .. versionchanged:: 2.4
709            If `name` is a :class:`Template` object it is returned from the
710            function unchanged.
711         """
712         if isinstance(name, Template):
713             return name
714         if parent is not None:
715             name = self.join_path(name, parent)
716         return self._load_template(name, self.make_globals(globals))
717
718     @internalcode
719     def select_template(self, names, parent=None, globals=None):
720         """Works like :meth:`get_template` but tries a number of templates
721         before it fails.  If it cannot find any of the templates, it will
722         raise a :exc:`TemplatesNotFound` exception.
723
724         .. versionadded:: 2.3
725
726         .. versionchanged:: 2.4
727            If `names` contains a :class:`Template` object it is returned
728            from the function unchanged.
729         """
730         if not names:
731             raise TemplatesNotFound(message=u'Tried to select from an empty list '
732                                             u'of templates.')
733         globals = self.make_globals(globals)
734         for name in names:
735             if isinstance(name, Template):
736                 return name
737             if parent is not None:
738                 name = self.join_path(name, parent)
739             try:
740                 return self._load_template(name, globals)
741             except TemplateNotFound:
742                 pass
743         raise TemplatesNotFound(names)
744
745     @internalcode
746     def get_or_select_template(self, template_name_or_list,
747                                parent=None, globals=None):
748         """Does a typecheck and dispatches to :meth:`select_template`
749         if an iterable of template names is given, otherwise to
750         :meth:`get_template`.
751
752         .. versionadded:: 2.3
753         """
754         if isinstance(template_name_or_list, basestring):
755             return self.get_template(template_name_or_list, parent, globals)
756         elif isinstance(template_name_or_list, Template):
757             return template_name_or_list
758         return self.select_template(template_name_or_list, parent, globals)
759
760     def from_string(self, source, globals=None, template_class=None):
761         """Load a template from a string.  This parses the source given and
762         returns a :class:`Template` object.
763         """
764         globals = self.make_globals(globals)
765         cls = template_class or self.template_class
766         return cls.from_code(self, self.compile(source), globals, None)
767
768     def make_globals(self, d):
769         """Return a dict for the globals."""
770         if not d:
771             return self.globals
772         return dict(self.globals, **d)
773
774
775 class Template(object):
776     """The central template object.  This class represents a compiled template
777     and is used to evaluate it.
778
779     Normally the template object is generated from an :class:`Environment` but
780     it also has a constructor that makes it possible to create a template
781     instance directly using the constructor.  It takes the same arguments as
782     the environment constructor but it's not possible to specify a loader.
783
784     Every template object has a few methods and members that are guaranteed
785     to exist.  However it's important that a template object should be
786     considered immutable.  Modifications on the object are not supported.
787
788     Template objects created from the constructor rather than an environment
789     do have an `environment` attribute that points to a temporary environment
790     that is probably shared with other templates created with the constructor
791     and compatible settings.
792
793     >>> template = Template('Hello {{ name }}!')
794     >>> template.render(name='John Doe')
795     u'Hello John Doe!'
796
797     >>> stream = template.stream(name='John Doe')
798     >>> stream.next()
799     u'Hello John Doe!'
800     >>> stream.next()
801     Traceback (most recent call last):
802         ...
803     StopIteration
804     """
805
806     def __new__(cls, source,
807                 block_start_string=BLOCK_START_STRING,
808                 block_end_string=BLOCK_END_STRING,
809                 variable_start_string=VARIABLE_START_STRING,
810                 variable_end_string=VARIABLE_END_STRING,
811                 comment_start_string=COMMENT_START_STRING,
812                 comment_end_string=COMMENT_END_STRING,
813                 line_statement_prefix=LINE_STATEMENT_PREFIX,
814                 line_comment_prefix=LINE_COMMENT_PREFIX,
815                 trim_blocks=TRIM_BLOCKS,
816                 newline_sequence=NEWLINE_SEQUENCE,
817                 extensions=(),
818                 optimized=True,
819                 undefined=Undefined,
820                 finalize=None,
821                 autoescape=False):
822         env = get_spontaneous_environment(
823             block_start_string, block_end_string, variable_start_string,
824             variable_end_string, comment_start_string, comment_end_string,
825             line_statement_prefix, line_comment_prefix, trim_blocks,
826             newline_sequence, frozenset(extensions), optimized, undefined,
827             finalize, autoescape, None, 0, False, None)
828         return env.from_string(source, template_class=cls)
829
830     @classmethod
831     def from_code(cls, environment, code, globals, uptodate=None):
832         """Creates a template object from compiled code and the globals.  This
833         is used by the loaders and environment to create a template object.
834         """
835         namespace = {
836             'environment':  environment,
837             '__file__':     code.co_filename
838         }
839         exec code in namespace
840         rv = cls._from_namespace(environment, namespace, globals)
841         rv._uptodate = uptodate
842         return rv
843
844     @classmethod
845     def from_module_dict(cls, environment, module_dict, globals):
846         """Creates a template object from a module.  This is used by the
847         module loader to create a template object.
848
849         .. versionadded:: 2.4
850         """
851         return cls._from_namespace(environment, module_dict, globals)
852
853     @classmethod
854     def _from_namespace(cls, environment, namespace, globals):
855         t = object.__new__(cls)
856         t.environment = environment
857         t.globals = globals
858         t.name = namespace['name']
859         t.filename = namespace['__file__']
860         t.blocks = namespace['blocks']
861
862         # render function and module
863         t.root_render_func = namespace['root']
864         t._module = None
865
866         # debug and loader helpers
867         t._debug_info = namespace['debug_info']
868         t._uptodate = None
869
870         # store the reference
871         namespace['environment'] = environment
872         namespace['__jinja_template__'] = t
873
874         return t
875
876     def render(self, *args, **kwargs):
877         """This method accepts the same arguments as the `dict` constructor:
878         A dict, a dict subclass or some keyword arguments.  If no arguments
879         are given the context will be empty.  These two calls do the same::
880
881             template.render(knights='that say nih')
882             template.render({'knights': 'that say nih'})
883
884         This will return the rendered template as unicode string.
885         """
886         vars = dict(*args, **kwargs)
887         try:
888             return concat(self.root_render_func(self.new_context(vars)))
889         except:
890             exc_info = sys.exc_info()
891         return self.environment.handle_exception(exc_info, True)
892
893     def stream(self, *args, **kwargs):
894         """Works exactly like :meth:`generate` but returns a
895         :class:`TemplateStream`.
896         """
897         return TemplateStream(self.generate(*args, **kwargs))
898
899     def generate(self, *args, **kwargs):
900         """For very large templates it can be useful to not render the whole
901         template at once but evaluate each statement after another and yield
902         piece for piece.  This method basically does exactly that and returns
903         a generator that yields one item after another as unicode strings.
904
905         It accepts the same arguments as :meth:`render`.
906         """
907         vars = dict(*args, **kwargs)
908         try:
909             for event in self.root_render_func(self.new_context(vars)):
910                 yield event
911         except:
912             exc_info = sys.exc_info()
913         else:
914             return
915         yield self.environment.handle_exception(exc_info, True)
916
917     def new_context(self, vars=None, shared=False, locals=None):
918         """Create a new :class:`Context` for this template.  The vars
919         provided will be passed to the template.  Per default the globals
920         are added to the context.  If shared is set to `True` the data
921         is passed as it to the context without adding the globals.
922
923         `locals` can be a dict of local variables for internal usage.
924         """
925         return new_context(self.environment, self.name, self.blocks,
926                            vars, shared, self.globals, locals)
927
928     def make_module(self, vars=None, shared=False, locals=None):
929         """This method works like the :attr:`module` attribute when called
930         without arguments but it will evaluate the template on every call
931         rather than caching it.  It's also possible to provide
932         a dict which is then used as context.  The arguments are the same
933         as for the :meth:`new_context` method.
934         """
935         return TemplateModule(self, self.new_context(vars, shared, locals))
936
937     @property
938     def module(self):
939         """The template as module.  This is used for imports in the
940         template runtime but is also useful if one wants to access
941         exported template variables from the Python layer:
942
943         >>> t = Template('{% macro foo() %}42{% endmacro %}23')
944         >>> unicode(t.module)
945         u'23'
946         >>> t.module.foo()
947         u'42'
948         """
949         if self._module is not None:
950             return self._module
951         self._module = rv = self.make_module()
952         return rv
953
954     def get_corresponding_lineno(self, lineno):
955         """Return the source line number of a line number in the
956         generated bytecode as they are not in sync.
957         """
958         for template_line, code_line in reversed(self.debug_info):
959             if code_line <= lineno:
960                 return template_line
961         return 1
962
963     @property
964     def is_up_to_date(self):
965         """If this variable is `False` there is a newer version available."""
966         if self._uptodate is None:
967             return True
968         return self._uptodate()
969
970     @property
971     def debug_info(self):
972         """The debug info mapping."""
973         return [tuple(map(int, x.split('='))) for x in
974                 self._debug_info.split('&')]
975
976     def __repr__(self):
977         if self.name is None:
978             name = 'memory:%x' % id(self)
979         else:
980             name = repr(self.name)
981         return '<%s %s>' % (self.__class__.__name__, name)
982
983
984 class TemplateModule(object):
985     """Represents an imported template.  All the exported names of the
986     template are available as attributes on this object.  Additionally
987     converting it into an unicode- or bytestrings renders the contents.
988     """
989
990     def __init__(self, template, context):
991         self._body_stream = list(template.root_render_func(context))
992         self.__dict__.update(context.get_exported())
993         self.__name__ = template.name
994
995     def __html__(self):
996         return Markup(concat(self._body_stream))
997
998     def __str__(self):
999         return unicode(self).encode('utf-8')
1000
1001     # unicode goes after __str__ because we configured 2to3 to rename
1002     # __unicode__ to __str__.  because the 2to3 tree is not designed to
1003     # remove nodes from it, we leave the above __str__ around and let
1004     # it override at runtime.
1005     def __unicode__(self):
1006         return concat(self._body_stream)
1007
1008     def __repr__(self):
1009         if self.__name__ is None:
1010             name = 'memory:%x' % id(self)
1011         else:
1012             name = repr(self.__name__)
1013         return '<%s %s>' % (self.__class__.__name__, name)
1014
1015
1016 class TemplateExpression(object):
1017     """The :meth:`jinja2.Environment.compile_expression` method returns an
1018     instance of this object.  It encapsulates the expression-like access
1019     to the template with an expression it wraps.
1020     """
1021
1022     def __init__(self, template, undefined_to_none):
1023         self._template = template
1024         self._undefined_to_none = undefined_to_none
1025
1026     def __call__(self, *args, **kwargs):
1027         context = self._template.new_context(dict(*args, **kwargs))
1028         consume(self._template.root_render_func(context))
1029         rv = context.vars['result']
1030         if self._undefined_to_none and isinstance(rv, Undefined):
1031             rv = None
1032         return rv
1033
1034
1035 class TemplateStream(object):
1036     """A template stream works pretty much like an ordinary python generator
1037     but it can buffer multiple items to reduce the number of total iterations.
1038     Per default the output is unbuffered which means that for every unbuffered
1039     instruction in the template one unicode string is yielded.
1040
1041     If buffering is enabled with a buffer size of 5, five items are combined
1042     into a new unicode string.  This is mainly useful if you are streaming
1043     big templates to a client via WSGI which flushes after each iteration.
1044     """
1045
1046     def __init__(self, gen):
1047         self._gen = gen
1048         self.disable_buffering()
1049
1050     def dump(self, fp, encoding=None, errors='strict'):
1051         """Dump the complete stream into a file or file-like object.
1052         Per default unicode strings are written, if you want to encode
1053         before writing specifiy an `encoding`.
1054
1055         Example usage::
1056
1057             Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
1058         """
1059         close = False
1060         if isinstance(fp, basestring):
1061             fp = file(fp, 'w')
1062             close = True
1063         try:
1064             if encoding is not None:
1065                 iterable = (x.encode(encoding, errors) for x in self)
1066             else:
1067                 iterable = self
1068             if hasattr(fp, 'writelines'):
1069                 fp.writelines(iterable)
1070             else:
1071                 for item in iterable:
1072                     fp.write(item)
1073         finally:
1074             if close:
1075                 fp.close()
1076
1077     def disable_buffering(self):
1078         """Disable the output buffering."""
1079         self._next = self._gen.next
1080         self.buffered = False
1081
1082     def enable_buffering(self, size=5):
1083         """Enable buffering.  Buffer `size` items before yielding them."""
1084         if size <= 1:
1085             raise ValueError('buffer size too small')
1086
1087         def generator(next):
1088             buf = []
1089             c_size = 0
1090             push = buf.append
1091
1092             while 1:
1093                 try:
1094                     while c_size < size:
1095                         c = next()
1096                         push(c)
1097                         if c:
1098                             c_size += 1
1099                 except StopIteration:
1100                     if not c_size:
1101                         return
1102                 yield concat(buf)
1103                 del buf[:]
1104                 c_size = 0
1105
1106         self.buffered = True
1107         self._next = generator(self._gen.next).next
1108
1109     def __iter__(self):
1110         return self
1111
1112     def next(self):
1113         return self._next()
1114
1115
1116 # hook in default template class.  if anyone reads this comment: ignore that
1117 # it's possible to use custom templates ;-)
1118 Environment.template_class = Template