Template to module compilation should work on 3.x now.
[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`.
164
165         `loader`
166             The template loader for this environment.
167
168         `cache_size`
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.
174
175         `auto_reload`
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
181             disable that.
182
183         `bytecode_cache`
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.
187
188             See :ref:`bytecode-cache` for more information.
189     """
190
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
194     sandboxed = False
195
196     #: True if the environment is just an overlay
197     overlayed = False
198
199     #: the environment this environment is linked to if it is an overlay
200     linked_to = None
201
202     #: shared environments have this set to `True`.  A shared environment
203     #: must not be modified
204     shared = False
205
206     #: these are currently EXPERIMENTAL undocumented features.
207     exception_handler = None
208     exception_formatter = None
209
210     def __init__(self,
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,
221                  extensions=(),
222                  optimized=True,
223                  undefined=Undefined,
224                  finalize=None,
225                  autoescape=False,
226                  loader=None,
227                  cache_size=50,
228                  auto_reload=True,
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)
236         #       -   unittests
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
239         #   existing already.
240
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
252
253         # runtime information
254         self.undefined = undefined
255         self.optimized = optimized
256         self.finalize = finalize
257         self.autoescape = autoescape
258
259         # defaults
260         self.filters = DEFAULT_FILTERS.copy()
261         self.tests = DEFAULT_TESTS.copy()
262         self.globals = DEFAULT_NAMESPACE.copy()
263
264         # set the loader provided
265         self.loader = loader
266         self.bytecode_cache = None
267         self.cache = create_cache(cache_size)
268         self.bytecode_cache = bytecode_cache
269         self.auto_reload = auto_reload
270
271         # load extensions
272         self.extensions = load_extensions(self, extensions)
273
274         _environment_sanity_check(self)
275
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.
280         """
281         for key, value in attributes.iteritems():
282             if not hasattr(self, key):
283                 setattr(self, key, value)
284
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.
298
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
302         through.
303         """
304         args = dict(locals())
305         del args['self'], args['cache_size'], args['extensions']
306
307         rv = object.__new__(self.__class__)
308         rv.__dict__.update(self.__dict__)
309         rv.overlayed = True
310         rv.linked_to = self
311
312         for key, value in args.iteritems():
313             if value is not missing:
314                 setattr(rv, key, value)
315
316         if cache_size is not missing:
317             rv.cache = create_cache(cache_size)
318         else:
319             rv.cache = copy_cache(self.cache)
320
321         rv.extensions = {}
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))
326
327         return _environment_sanity_check(rv)
328
329     lexer = property(get_lexer, doc="The lexer for this environment.")
330
331     def getitem(self, obj, argument):
332         """Get an item or attribute of an object but prefer the item."""
333         try:
334             return obj[argument]
335         except (TypeError, LookupError):
336             if isinstance(argument, basestring):
337                 try:
338                     attr = str(argument)
339                 except:
340                     pass
341                 else:
342                     try:
343                         return getattr(obj, attr)
344                     except AttributeError:
345                         pass
346             return self.undefined(obj=obj, name=argument)
347
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.
351         """
352         try:
353             return getattr(obj, attribute)
354         except AttributeError:
355             pass
356         try:
357             return obj[attribute]
358         except (TypeError, LookupError, AttributeError):
359             return self.undefined(obj=obj, name=attribute)
360
361     @internalcode
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.
367
368         If you are :ref:`developing Jinja2 extensions <writing-extensions>`
369         this gives you a good overview of the node tree generated.
370         """
371         try:
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)
376
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()
380
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.
386
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.
390         """
391         source = unicode(source)
392         try:
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)
397
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.
402         """
403         return reduce(lambda s, e: e.preprocess(s, name, filename),
404                       self.extensions.itervalues(), unicode(source))
405
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`.
409         """
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)
416         return stream
417
418     @internalcode
419     def compile(self, source, name=None, filename=None, raw=False,
420                 defer_init=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
426         can be omitted.
427
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.
432
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.
436
437         .. versionadded:: 2.4
438            `defer_init` parameter added.
439         """
440         source_hint = None
441         try:
442             if isinstance(source, basestring):
443                 source_hint = source
444                 source = self._parse(source, name, filename)
445             if self.optimized:
446                 source = optimize(source, self)
447             source = generate(source, self, name, filename,
448                               defer_init=defer_init)
449             if raw:
450                 return source
451             if filename is None:
452                 filename = '<template>'
453             else:
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)
459
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.
464
465         This is useful if applications want to use the same rules as Jinja
466         in template "configuration files" or similar situations.
467
468         Example usage:
469
470         >>> env = Environment()
471         >>> expr = env.compile_expression('foo == 42')
472         >>> expr(foo=23)
473         False
474         >>> expr(foo=42)
475         True
476
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`.
480
481         >>> env.compile_expression('var')() is None
482         True
483         >>> env.compile_expression('var', undefined_to_none=False)()
484         Undefined
485
486         .. versionadded:: 2.1
487         """
488         parser = Parser(self, source, state='variable')
489         exc_info = None
490         try:
491             expr = parser.parse_expression()
492             if not parser.stream.eos:
493                 raise TemplateSyntaxError('chunk after expression',
494                                           parser.stream.current.lineno,
495                                           None, None)
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)
504
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'``.
513
514         `extensions` and `filter_func` are passed to :meth:`list_templates`.
515         Each template returned will be compiled to the target folder or
516         zipfile.
517
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.
522
523         If `py_compile` is set to `True` .pyc files will be written to the
524         target instead of standard .py files.
525
526         .. versionadded:: 2.4
527         """
528         from jinja2.loaders import ModuleLoader
529
530         if log_function is None:
531             log_function = lambda x: None
532
533         if py_compile:
534             import imp, struct, marshal
535             py_header = imp.get_magic() + \
536                 u'\xff\xff\xff\xff'.encode('iso-8859-15')
537
538         def write_file(filename, data, mode):
539             if zip:
540                 info = ZipInfo(filename)
541                 info.external_attr = 0755 << 16L
542                 zip_file.writestr(info, data)
543             else:
544                 f = open(os.path.join(target, filename), mode)
545                 try:
546                     f.write(data)
547                 finally:
548                     f.close()
549
550         if zip is not None:
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)
555         else:
556             if not os.path.isdir(target):
557                 os.makedirs(target)
558             log_function('Compiling into folder "%s"' % target)
559
560         try:
561             for name in self.list_templates(extensions, filter_func):
562                 source, filename, _ = self.loader.get_source(self, name)
563                 try:
564                     code = self.compile(source, name, filename, True, True)
565                 except TemplateSyntaxError, e:
566                     if not ignore_errors:
567                         raise
568                     log_function('Could not compile "%s": %s' % (name, e))
569                     continue
570
571                 filename = ModuleLoader.get_module_filename(name)
572
573                 if py_compile:
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'))
579                 else:
580                     write_file(filename, code, 'w')
581                     log_function('Compiled "%s" as %s' % (name, filename))
582         finally:
583             if zip:
584                 zip_file.close()
585
586         log_function('Finished compiling templates')
587
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.
592
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
598         in the result list.
599
600         If the loader does not support that, a :exc:`TypeError` is raised.
601         """
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)
611         return x
612
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.
616         """
617         global _make_traceback
618         if exc_info is None:
619             exc_info = sys.exc_info()
620
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
624         # all of that.
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
634
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
640         template name.
641
642         Subclasses may override this method and implement template path
643         joining here.
644         """
645         return template
646
647     @internalcode
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):
655                 return template
656         template = self.loader.load(self, name, globals)
657         if self.cache is not None:
658             self.cache[name] = template
659         return template
660
661     @internalcode
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.
667
668         The `globals` parameter can be used to provide template wide globals.
669         These variables are available in the context at render time.
670
671         If the template does not exist a :exc:`TemplateNotFound` exception is
672         raised.
673
674         .. versionchanged:: 2.4
675            If `name` is a :class:`Template` object it is returned from the
676            function unchanged.
677         """
678         if isinstance(name, Template):
679             return name
680         if parent is not None:
681             name = self.join_path(name, parent)
682         return self._load_template(name, self.make_globals(globals))
683
684     @internalcode
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.
689
690         .. versionadded:: 2.3
691
692         .. versionchanged:: 2.4
693            If `names` contains a :class:`Template` object it is returned
694            from the function unchanged.
695         """
696         if not names:
697             raise TemplatesNotFound(message=u'Tried to select from an empty list '
698                                             u'of templates.')
699         globals = self.make_globals(globals)
700         for name in names:
701             if isinstance(name, Template):
702                 return name
703             if parent is not None:
704                 name = self.join_path(name, parent)
705             try:
706                 return self._load_template(name, globals)
707             except TemplateNotFound:
708                 pass
709         raise TemplatesNotFound(names)
710
711     @internalcode
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`.
717
718         .. versionadded:: 2.3
719         """
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)
725
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.
729         """
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)
733
734     def make_globals(self, d):
735         """Return a dict for the globals."""
736         if not d:
737             return self.globals
738         return dict(self.globals, **d)
739
740
741 class Template(object):
742     """The central template object.  This class represents a compiled template
743     and is used to evaluate it.
744
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.
749
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.
753
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.
758
759     >>> template = Template('Hello {{ name }}!')
760     >>> template.render(name='John Doe')
761     u'Hello John Doe!'
762
763     >>> stream = template.stream(name='John Doe')
764     >>> stream.next()
765     u'Hello John Doe!'
766     >>> stream.next()
767     Traceback (most recent call last):
768         ...
769     StopIteration
770     """
771
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,
783                 extensions=(),
784                 optimized=True,
785                 undefined=Undefined,
786                 finalize=None,
787                 autoescape=False):
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)
795
796     @classmethod
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.
800         """
801         namespace = {
802             'environment':  environment,
803             '__file__':     code.co_filename
804         }
805         exec code in namespace
806         rv = cls._from_namespace(environment, namespace, globals)
807         rv._uptodate = uptodate
808         return rv
809
810     @classmethod
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.
814
815         .. versionadded:: 2.4
816         """
817         return cls._from_namespace(environment, module_dict, globals)
818
819     @classmethod
820     def _from_namespace(cls, environment, namespace, globals):
821         t = object.__new__(cls)
822         t.environment = environment
823         t.globals = globals
824         t.name = namespace['name']
825         t.filename = namespace['__file__']
826         t.blocks = namespace['blocks']
827
828         # render function and module
829         t.root_render_func = namespace['root']
830         t._module = None
831
832         # debug and loader helpers
833         t._debug_info = namespace['debug_info']
834         t._uptodate = None
835
836         # store the reference
837         namespace['environment'] = environment
838         namespace['__jinja_template__'] = t
839
840         return t
841
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::
846
847             template.render(knights='that say nih')
848             template.render({'knights': 'that say nih'})
849
850         This will return the rendered template as unicode string.
851         """
852         vars = dict(*args, **kwargs)
853         try:
854             return concat(self.root_render_func(self.new_context(vars)))
855         except:
856             exc_info = sys.exc_info()
857         return self.environment.handle_exception(exc_info, True)
858
859     def stream(self, *args, **kwargs):
860         """Works exactly like :meth:`generate` but returns a
861         :class:`TemplateStream`.
862         """
863         return TemplateStream(self.generate(*args, **kwargs))
864
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.
870
871         It accepts the same arguments as :meth:`render`.
872         """
873         vars = dict(*args, **kwargs)
874         try:
875             for event in self.root_render_func(self.new_context(vars)):
876                 yield event
877         except:
878             exc_info = sys.exc_info()
879         else:
880             return
881         yield self.environment.handle_exception(exc_info, True)
882
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.
888
889         `locals` can be a dict of local variables for internal usage.
890         """
891         return new_context(self.environment, self.name, self.blocks,
892                            vars, shared, self.globals, locals)
893
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.
900         """
901         return TemplateModule(self, self.new_context(vars, shared, locals))
902
903     @property
904     def module(self):
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:
908
909         >>> t = Template('{% macro foo() %}42{% endmacro %}23')
910         >>> unicode(t.module)
911         u'23'
912         >>> t.module.foo()
913         u'42'
914         """
915         if self._module is not None:
916             return self._module
917         self._module = rv = self.make_module()
918         return rv
919
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.
923         """
924         for template_line, code_line in reversed(self.debug_info):
925             if code_line <= lineno:
926                 return template_line
927         return 1
928
929     @property
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:
933             return True
934         return self._uptodate()
935
936     @property
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('&')]
941
942     def __repr__(self):
943         if self.name is None:
944             name = 'memory:%x' % id(self)
945         else:
946             name = repr(self.name)
947         return '<%s %s>' % (self.__class__.__name__, name)
948
949
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.
954     """
955
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
960
961     def __html__(self):
962         return Markup(concat(self._body_stream))
963
964     def __str__(self):
965         return unicode(self).encode('utf-8')
966
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)
973
974     def __repr__(self):
975         if self.__name__ is None:
976             name = 'memory:%x' % id(self)
977         else:
978             name = repr(self.__name__)
979         return '<%s %s>' % (self.__class__.__name__, name)
980
981
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.
986     """
987
988     def __init__(self, template, undefined_to_none):
989         self._template = template
990         self._undefined_to_none = undefined_to_none
991
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):
997             rv = None
998         return rv
999
1000
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.
1006
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.
1010     """
1011
1012     def __init__(self, gen):
1013         self._gen = gen
1014         self.disable_buffering()
1015
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`.
1020
1021         Example usage::
1022
1023             Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
1024         """
1025         close = False
1026         if isinstance(fp, basestring):
1027             fp = file(fp, 'w')
1028             close = True
1029         try:
1030             if encoding is not None:
1031                 iterable = (x.encode(encoding, errors) for x in self)
1032             else:
1033                 iterable = self
1034             if hasattr(fp, 'writelines'):
1035                 fp.writelines(iterable)
1036             else:
1037                 for item in iterable:
1038                     fp.write(item)
1039         finally:
1040             if close:
1041                 fp.close()
1042
1043     def disable_buffering(self):
1044         """Disable the output buffering."""
1045         self._next = self._gen.next
1046         self.buffered = False
1047
1048     def enable_buffering(self, size=5):
1049         """Enable buffering.  Buffer `size` items before yielding them."""
1050         if size <= 1:
1051             raise ValueError('buffer size too small')
1052
1053         def generator(next):
1054             buf = []
1055             c_size = 0
1056             push = buf.append
1057
1058             while 1:
1059                 try:
1060                     while c_size < size:
1061                         c = next()
1062                         push(c)
1063                         if c:
1064                             c_size += 1
1065                 except StopIteration:
1066                     if not c_size:
1067                         return
1068                 yield concat(buf)
1069                 del buf[:]
1070                 c_size = 0
1071
1072         self.buffered = True
1073         self._next = generator(self._gen.next).next
1074
1075     def __iter__(self):
1076         return self
1077
1078     def next(self):
1079         return self._next()
1080
1081
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