OLD | NEW |
1 # -*- coding: utf-8 -*- | 1 # -*- coding: utf-8 -*- |
2 """ | 2 """ |
3 jinja2.environment | 3 jinja2.environment |
4 ~~~~~~~~~~~~~~~~~~ | 4 ~~~~~~~~~~~~~~~~~~ |
5 | 5 |
6 Provides a class that holds runtime and parsing time options. | 6 Provides a class that holds runtime and parsing time options. |
7 | 7 |
8 :copyright: (c) 2010 by the Jinja Team. | 8 :copyright: (c) 2010 by the Jinja Team. |
9 :license: BSD, see LICENSE for more details. | 9 :license: BSD, see LICENSE for more details. |
10 """ | 10 """ |
11 import os | 11 import os |
12 import sys | 12 import sys |
13 from jinja2 import nodes | 13 from jinja2 import nodes |
14 from jinja2.defaults import BLOCK_START_STRING, \ | 14 from jinja2.defaults import BLOCK_START_STRING, \ |
15 BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \ | 15 BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \ |
16 COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \ | 16 COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \ |
17 LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \ | 17 LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \ |
18 DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \ | 18 DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \ |
19 KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS | 19 KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS |
20 from jinja2.lexer import get_lexer, TokenStream | 20 from jinja2.lexer import get_lexer, TokenStream |
21 from jinja2.parser import Parser | 21 from jinja2.parser import Parser |
22 from jinja2.nodes import EvalContext | 22 from jinja2.nodes import EvalContext |
23 from jinja2.optimizer import optimize | 23 from jinja2.optimizer import optimize |
24 from jinja2.compiler import generate | 24 from jinja2.compiler import generate, CodeGenerator |
25 from jinja2.runtime import Undefined, new_context | 25 from jinja2.runtime import Undefined, new_context, Context |
26 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \ | 26 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \ |
27 TemplatesNotFound, TemplateRuntimeError | 27 TemplatesNotFound, TemplateRuntimeError |
28 from jinja2.utils import import_string, LRUCache, Markup, missing, \ | 28 from jinja2.utils import import_string, LRUCache, Markup, missing, \ |
29 concat, consume, internalcode | 29 concat, consume, internalcode |
30 from jinja2._compat import imap, ifilter, string_types, iteritems, \ | 30 from jinja2._compat import imap, ifilter, string_types, iteritems, \ |
31 text_type, reraise, implements_iterator, implements_to_string, \ | 31 text_type, reraise, implements_iterator, implements_to_string, \ |
32 get_next, encode_filename, PY2, PYPY | 32 get_next, encode_filename, PY2, PYPY |
33 from functools import reduce | 33 from functools import reduce |
34 | 34 |
35 | 35 |
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
83 for extension in extensions: | 83 for extension in extensions: |
84 if isinstance(extension, string_types): | 84 if isinstance(extension, string_types): |
85 extension = import_string(extension) | 85 extension = import_string(extension) |
86 result[extension.identifier] = extension(environment) | 86 result[extension.identifier] = extension(environment) |
87 return result | 87 return result |
88 | 88 |
89 | 89 |
90 def _environment_sanity_check(environment): | 90 def _environment_sanity_check(environment): |
91 """Perform a sanity check on the environment.""" | 91 """Perform a sanity check on the environment.""" |
92 assert issubclass(environment.undefined, Undefined), 'undefined must ' \ | 92 assert issubclass(environment.undefined, Undefined), 'undefined must ' \ |
93 'be a subclass of undefined because filters depend on it.' | 93 'be a subclass of undefined because filters depend on it.' |
94 assert environment.block_start_string != \ | 94 assert environment.block_start_string != \ |
95 environment.variable_start_string != \ | 95 environment.variable_start_string != \ |
96 environment.comment_start_string, 'block, variable and comment ' \ | 96 environment.comment_start_string, 'block, variable and comment ' \ |
97 'start strings must be different' | 97 'start strings must be different' |
98 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ | 98 assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ |
99 'newline_sequence set to unknown line ending string.' | 99 'newline_sequence set to unknown line ending string.' |
100 return environment | 100 return environment |
101 | 101 |
102 | 102 |
103 class Environment(object): | 103 class Environment(object): |
104 r"""The core component of Jinja is the `Environment`. It contains | 104 r"""The core component of Jinja is the `Environment`. It contains |
105 important shared variables like configuration, filters, tests, | 105 important shared variables like configuration, filters, tests, |
106 globals and others. Instances of this class may be modified if | 106 globals and others. Instances of this class may be modified if |
107 they are not shared and if no template was loaded so far. | 107 they are not shared and if no template was loaded so far. |
108 Modifications on environments after the first template was loaded | 108 Modifications on environments after the first template was loaded |
109 will lead to surprising effects and undefined behavior. | 109 will lead to surprising effects and undefined behavior. |
110 | 110 |
111 Here the possible initialization parameters: | 111 Here are the possible initialization parameters: |
112 | 112 |
113 `block_start_string` | 113 `block_start_string` |
114 The string marking the begin of a block. Defaults to ``'{%'``. | 114 The string marking the beginning of a block. Defaults to ``'{%'``. |
115 | 115 |
116 `block_end_string` | 116 `block_end_string` |
117 The string marking the end of a block. Defaults to ``'%}'``. | 117 The string marking the end of a block. Defaults to ``'%}'``. |
118 | 118 |
119 `variable_start_string` | 119 `variable_start_string` |
120 The string marking the begin of a print statement. | 120 The string marking the beginning of a print statement. |
121 Defaults to ``'{{'``. | 121 Defaults to ``'{{'``. |
122 | 122 |
123 `variable_end_string` | 123 `variable_end_string` |
124 The string marking the end of a print statement. Defaults to | 124 The string marking the end of a print statement. Defaults to |
125 ``'}}'``. | 125 ``'}}'``. |
126 | 126 |
127 `comment_start_string` | 127 `comment_start_string` |
128 The string marking the begin of a comment. Defaults to ``'{#'``. | 128 The string marking the beginning of a comment. Defaults to ``'{#'``
. |
129 | 129 |
130 `comment_end_string` | 130 `comment_end_string` |
131 The string marking the end of a comment. Defaults to ``'#}'``. | 131 The string marking the end of a comment. Defaults to ``'#}'``. |
132 | 132 |
133 `line_statement_prefix` | 133 `line_statement_prefix` |
134 If given and a string, this will be used as prefix for line based | 134 If given and a string, this will be used as prefix for line based |
135 statements. See also :ref:`line-statements`. | 135 statements. See also :ref:`line-statements`. |
136 | 136 |
137 `line_comment_prefix` | 137 `line_comment_prefix` |
138 If given and a string, this will be used as prefix for line based | 138 If given and a string, this will be used as prefix for line based |
139 based comments. See also :ref:`line-statements`. | 139 comments. See also :ref:`line-statements`. |
140 | 140 |
141 .. versionadded:: 2.2 | 141 .. versionadded:: 2.2 |
142 | 142 |
143 `trim_blocks` | 143 `trim_blocks` |
144 If this is set to ``True`` the first newline after a block is | 144 If this is set to ``True`` the first newline after a block is |
145 removed (block, not variable tag!). Defaults to `False`. | 145 removed (block, not variable tag!). Defaults to `False`. |
146 | 146 |
147 `lstrip_blocks` | 147 `lstrip_blocks` |
148 If this is set to ``True`` leading spaces and tabs are stripped | 148 If this is set to ``True`` leading spaces and tabs are stripped |
149 from the start of a line to a block. Defaults to `False`. | 149 from the start of a line to a block. Defaults to `False`. |
(...skipping 23 matching lines...) Expand all Loading... |
173 :class:`Undefined` or a subclass of it that is used to represent | 173 :class:`Undefined` or a subclass of it that is used to represent |
174 undefined values in the template. | 174 undefined values in the template. |
175 | 175 |
176 `finalize` | 176 `finalize` |
177 A callable that can be used to process the result of a variable | 177 A callable that can be used to process the result of a variable |
178 expression before it is output. For example one can convert | 178 expression before it is output. For example one can convert |
179 `None` implicitly into an empty string here. | 179 `None` implicitly into an empty string here. |
180 | 180 |
181 `autoescape` | 181 `autoescape` |
182 If set to true the XML/HTML autoescaping feature is enabled by | 182 If set to true the XML/HTML autoescaping feature is enabled by |
183 default. For more details about auto escaping see | 183 default. For more details about autoescaping see |
184 :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also | 184 :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also |
185 be a callable that is passed the template name and has to | 185 be a callable that is passed the template name and has to |
186 return `True` or `False` depending on autoescape should be | 186 return `True` or `False` depending on autoescape should be |
187 enabled by default. | 187 enabled by default. |
188 | 188 |
189 .. versionchanged:: 2.4 | 189 .. versionchanged:: 2.4 |
190 `autoescape` can now be a function | 190 `autoescape` can now be a function |
191 | 191 |
192 `loader` | 192 `loader` |
193 The template loader for this environment. | 193 The template loader for this environment. |
194 | 194 |
195 `cache_size` | 195 `cache_size` |
196 The size of the cache. Per default this is ``50`` which means | 196 The size of the cache. Per default this is ``400`` which means |
197 that if more than 50 templates are loaded the loader will clean | 197 that if more than 400 templates are loaded the loader will clean |
198 out the least recently used template. If the cache size is set to | 198 out the least recently used template. If the cache size is set to |
199 ``0`` templates are recompiled all the time, if the cache size is | 199 ``0`` templates are recompiled all the time, if the cache size is |
200 ``-1`` the cache will not be cleaned. | 200 ``-1`` the cache will not be cleaned. |
201 | 201 |
| 202 .. versionchanged:: 2.8 |
| 203 The cache size was increased to 400 from a low 50. |
| 204 |
202 `auto_reload` | 205 `auto_reload` |
203 Some loaders load templates from locations where the template | 206 Some loaders load templates from locations where the template |
204 sources may change (ie: file system or database). If | 207 sources may change (ie: file system or database). If |
205 `auto_reload` is set to `True` (default) every time a template is | 208 `auto_reload` is set to `True` (default) every time a template is |
206 requested the loader checks if the source changed and if yes, it | 209 requested the loader checks if the source changed and if yes, it |
207 will reload the template. For higher performance it's possible to | 210 will reload the template. For higher performance it's possible to |
208 disable that. | 211 disable that. |
209 | 212 |
210 `bytecode_cache` | 213 `bytecode_cache` |
211 If set to a bytecode cache object, this object will provide a | 214 If set to a bytecode cache object, this object will provide a |
(...skipping 16 matching lines...) Expand all Loading... |
228 linked_to = None | 231 linked_to = None |
229 | 232 |
230 #: shared environments have this set to `True`. A shared environment | 233 #: shared environments have this set to `True`. A shared environment |
231 #: must not be modified | 234 #: must not be modified |
232 shared = False | 235 shared = False |
233 | 236 |
234 #: these are currently EXPERIMENTAL undocumented features. | 237 #: these are currently EXPERIMENTAL undocumented features. |
235 exception_handler = None | 238 exception_handler = None |
236 exception_formatter = None | 239 exception_formatter = None |
237 | 240 |
| 241 #: the class that is used for code generation. See |
| 242 #: :class:`~jinja2.compiler.CodeGenerator` for more information. |
| 243 code_generator_class = CodeGenerator |
| 244 |
| 245 #: the context class thatis used for templates. See |
| 246 #: :class:`~jinja2.runtime.Context` for more information. |
| 247 context_class = Context |
| 248 |
238 def __init__(self, | 249 def __init__(self, |
239 block_start_string=BLOCK_START_STRING, | 250 block_start_string=BLOCK_START_STRING, |
240 block_end_string=BLOCK_END_STRING, | 251 block_end_string=BLOCK_END_STRING, |
241 variable_start_string=VARIABLE_START_STRING, | 252 variable_start_string=VARIABLE_START_STRING, |
242 variable_end_string=VARIABLE_END_STRING, | 253 variable_end_string=VARIABLE_END_STRING, |
243 comment_start_string=COMMENT_START_STRING, | 254 comment_start_string=COMMENT_START_STRING, |
244 comment_end_string=COMMENT_END_STRING, | 255 comment_end_string=COMMENT_END_STRING, |
245 line_statement_prefix=LINE_STATEMENT_PREFIX, | 256 line_statement_prefix=LINE_STATEMENT_PREFIX, |
246 line_comment_prefix=LINE_COMMENT_PREFIX, | 257 line_comment_prefix=LINE_COMMENT_PREFIX, |
247 trim_blocks=TRIM_BLOCKS, | 258 trim_blocks=TRIM_BLOCKS, |
248 lstrip_blocks=LSTRIP_BLOCKS, | 259 lstrip_blocks=LSTRIP_BLOCKS, |
249 newline_sequence=NEWLINE_SEQUENCE, | 260 newline_sequence=NEWLINE_SEQUENCE, |
250 keep_trailing_newline=KEEP_TRAILING_NEWLINE, | 261 keep_trailing_newline=KEEP_TRAILING_NEWLINE, |
251 extensions=(), | 262 extensions=(), |
252 optimized=True, | 263 optimized=True, |
253 undefined=Undefined, | 264 undefined=Undefined, |
254 finalize=None, | 265 finalize=None, |
255 autoescape=False, | 266 autoescape=False, |
256 loader=None, | 267 loader=None, |
257 cache_size=50, | 268 cache_size=400, |
258 auto_reload=True, | 269 auto_reload=True, |
259 bytecode_cache=None): | 270 bytecode_cache=None): |
260 # !!Important notice!! | 271 # !!Important notice!! |
261 # The constructor accepts quite a few arguments that should be | 272 # The constructor accepts quite a few arguments that should be |
262 # passed by keyword rather than position. However it's important to | 273 # passed by keyword rather than position. However it's important to |
263 # not change the order of arguments because it's used at least | 274 # not change the order of arguments because it's used at least |
264 # internally in those cases: | 275 # internally in those cases: |
265 # - spontaneous environments (i18n extension and Template) | 276 # - spontaneous environments (i18n extension and Template) |
266 # - unittests | 277 # - unittests |
267 # If parameter changes are required only add parameters at the end | 278 # If parameter changes are required only add parameters at the end |
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
323 def overlay(self, block_start_string=missing, block_end_string=missing, | 334 def overlay(self, block_start_string=missing, block_end_string=missing, |
324 variable_start_string=missing, variable_end_string=missing, | 335 variable_start_string=missing, variable_end_string=missing, |
325 comment_start_string=missing, comment_end_string=missing, | 336 comment_start_string=missing, comment_end_string=missing, |
326 line_statement_prefix=missing, line_comment_prefix=missing, | 337 line_statement_prefix=missing, line_comment_prefix=missing, |
327 trim_blocks=missing, lstrip_blocks=missing, | 338 trim_blocks=missing, lstrip_blocks=missing, |
328 extensions=missing, optimized=missing, | 339 extensions=missing, optimized=missing, |
329 undefined=missing, finalize=missing, autoescape=missing, | 340 undefined=missing, finalize=missing, autoescape=missing, |
330 loader=missing, cache_size=missing, auto_reload=missing, | 341 loader=missing, cache_size=missing, auto_reload=missing, |
331 bytecode_cache=missing): | 342 bytecode_cache=missing): |
332 """Create a new overlay environment that shares all the data with the | 343 """Create a new overlay environment that shares all the data with the |
333 current environment except of cache and the overridden attributes. | 344 current environment except for cache and the overridden attributes. |
334 Extensions cannot be removed for an overlayed environment. An overlayed | 345 Extensions cannot be removed for an overlayed environment. An overlayed |
335 environment automatically gets all the extensions of the environment it | 346 environment automatically gets all the extensions of the environment it |
336 is linked to plus optional extra extensions. | 347 is linked to plus optional extra extensions. |
337 | 348 |
338 Creating overlays should happen after the initial environment was set | 349 Creating overlays should happen after the initial environment was set |
339 up completely. Not all attributes are truly linked, some are just | 350 up completely. Not all attributes are truly linked, some are just |
340 copied over so modifications on the original environment may not shine | 351 copied over so modifications on the original environment may not shine |
341 through. | 352 through. |
342 """ | 353 """ |
343 args = dict(locals()) | 354 args = dict(locals()) |
(...skipping 200 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
544 defer_init=defer_init) | 555 defer_init=defer_init) |
545 if raw: | 556 if raw: |
546 return source | 557 return source |
547 if filename is None: | 558 if filename is None: |
548 filename = '<template>' | 559 filename = '<template>' |
549 else: | 560 else: |
550 filename = encode_filename(filename) | 561 filename = encode_filename(filename) |
551 return self._compile(source, filename) | 562 return self._compile(source, filename) |
552 except TemplateSyntaxError: | 563 except TemplateSyntaxError: |
553 exc_info = sys.exc_info() | 564 exc_info = sys.exc_info() |
554 self.handle_exception(exc_info, source_hint=source) | 565 self.handle_exception(exc_info, source_hint=source_hint) |
555 | 566 |
556 def compile_expression(self, source, undefined_to_none=True): | 567 def compile_expression(self, source, undefined_to_none=True): |
557 """A handy helper method that returns a callable that accepts keyword | 568 """A handy helper method that returns a callable that accepts keyword |
558 arguments that appear as variables in the expression. If called it | 569 arguments that appear as variables in the expression. If called it |
559 returns the result of the expression. | 570 returns the result of the expression. |
560 | 571 |
561 This is useful if applications want to use the same rules as Jinja | 572 This is useful if applications want to use the same rules as Jinja |
562 in template "configuration files" or similar situations. | 573 in template "configuration files" or similar situations. |
563 | 574 |
564 Example usage: | 575 Example usage: |
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
596 self.handle_exception(exc_info, source_hint=source) | 607 self.handle_exception(exc_info, source_hint=source) |
597 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)] | 608 body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)] |
598 template = self.from_string(nodes.Template(body, lineno=1)) | 609 template = self.from_string(nodes.Template(body, lineno=1)) |
599 return TemplateExpression(template, undefined_to_none) | 610 return TemplateExpression(template, undefined_to_none) |
600 | 611 |
601 def compile_templates(self, target, extensions=None, filter_func=None, | 612 def compile_templates(self, target, extensions=None, filter_func=None, |
602 zip='deflated', log_function=None, | 613 zip='deflated', log_function=None, |
603 ignore_errors=True, py_compile=False): | 614 ignore_errors=True, py_compile=False): |
604 """Finds all the templates the loader can find, compiles them | 615 """Finds all the templates the loader can find, compiles them |
605 and stores them in `target`. If `zip` is `None`, instead of in a | 616 and stores them in `target`. If `zip` is `None`, instead of in a |
606 zipfile, the templates will be will be stored in a directory. | 617 zipfile, the templates will be stored in a directory. |
607 By default a deflate zip algorithm is used, to switch to | 618 By default a deflate zip algorithm is used. To switch to |
608 the stored algorithm, `zip` can be set to ``'stored'``. | 619 the stored algorithm, `zip` can be set to ``'stored'``. |
609 | 620 |
610 `extensions` and `filter_func` are passed to :meth:`list_templates`. | 621 `extensions` and `filter_func` are passed to :meth:`list_templates`. |
611 Each template returned will be compiled to the target folder or | 622 Each template returned will be compiled to the target folder or |
612 zipfile. | 623 zipfile. |
613 | 624 |
614 By default template compilation errors are ignored. In case a | 625 By default template compilation errors are ignored. In case a |
615 log function is provided, errors are logged. If you want template | 626 log function is provided, errors are logged. If you want template |
616 syntax errors to abort the compilation you can set `ignore_errors` | 627 syntax errors to abort the compilation you can set `ignore_errors` |
617 to `False` and you will get an exception on syntax errors. | 628 to `False` and you will get an exception on syntax errors. |
618 | 629 |
619 If `py_compile` is set to `True` .pyc files will be written to the | 630 If `py_compile` is set to `True` .pyc files will be written to the |
620 target instead of standard .py files. This flag does not do anything | 631 target instead of standard .py files. This flag does not do anything |
621 on pypy and Python 3 where pyc files are not picked up by itself and | 632 on pypy and Python 3 where pyc files are not picked up by itself and |
622 don't give much benefit. | 633 don't give much benefit. |
623 | 634 |
624 .. versionadded:: 2.4 | 635 .. versionadded:: 2.4 |
625 """ | 636 """ |
626 from jinja2.loaders import ModuleLoader | 637 from jinja2.loaders import ModuleLoader |
627 | 638 |
628 if log_function is None: | 639 if log_function is None: |
629 log_function = lambda x: None | 640 log_function = lambda x: None |
630 | 641 |
631 if py_compile: | 642 if py_compile: |
632 if not PY2 or PYPY: | 643 if not PY2 or PYPY: |
633 from warnings import warn | 644 from warnings import warn |
634 warn(Warning('py_compile has no effect on pypy or Python 3')) | 645 warn(Warning('py_compile has no effect on pypy or Python 3')) |
635 py_compile = False | 646 py_compile = False |
636 else: | 647 else: |
637 import imp, marshal | 648 import imp |
| 649 import marshal |
638 py_header = imp.get_magic() + \ | 650 py_header = imp.get_magic() + \ |
639 u'\xff\xff\xff\xff'.encode('iso-8859-15') | 651 u'\xff\xff\xff\xff'.encode('iso-8859-15') |
640 | 652 |
641 # Python 3.3 added a source filesize to the header | 653 # Python 3.3 added a source filesize to the header |
642 if sys.version_info >= (3, 3): | 654 if sys.version_info >= (3, 3): |
643 py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15') | 655 py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15') |
644 | 656 |
645 def write_file(filename, data, mode): | 657 def write_file(filename, data, mode): |
646 if zip: | 658 if zip: |
647 info = ZipInfo(filename) | 659 info = ZipInfo(filename) |
(...skipping 61 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
709 .. versionadded:: 2.4 | 721 .. versionadded:: 2.4 |
710 """ | 722 """ |
711 x = self.loader.list_templates() | 723 x = self.loader.list_templates() |
712 if extensions is not None: | 724 if extensions is not None: |
713 if filter_func is not None: | 725 if filter_func is not None: |
714 raise TypeError('either extensions or filter_func ' | 726 raise TypeError('either extensions or filter_func ' |
715 'can be passed, but not both') | 727 'can be passed, but not both') |
716 filter_func = lambda x: '.' in x and \ | 728 filter_func = lambda x: '.' in x and \ |
717 x.rsplit('.', 1)[1] in extensions | 729 x.rsplit('.', 1)[1] in extensions |
718 if filter_func is not None: | 730 if filter_func is not None: |
719 x = ifilter(filter_func, x) | 731 x = list(ifilter(filter_func, x)) |
720 return x | 732 return x |
721 | 733 |
722 def handle_exception(self, exc_info=None, rendered=False, source_hint=None): | 734 def handle_exception(self, exc_info=None, rendered=False, source_hint=None): |
723 """Exception handling helper. This is used internally to either raise | 735 """Exception handling helper. This is used internally to either raise |
724 rewritten exceptions or return a rendered traceback for the template. | 736 rewritten exceptions or return a rendered traceback for the template. |
725 """ | 737 """ |
726 global _make_traceback | 738 global _make_traceback |
727 if exc_info is None: | 739 if exc_info is None: |
728 exc_info = sys.exc_info() | 740 exc_info = sys.exc_info() |
729 | 741 |
(...skipping 20 matching lines...) Expand all Loading... |
750 | 762 |
751 Subclasses may override this method and implement template path | 763 Subclasses may override this method and implement template path |
752 joining here. | 764 joining here. |
753 """ | 765 """ |
754 return template | 766 return template |
755 | 767 |
756 @internalcode | 768 @internalcode |
757 def _load_template(self, name, globals): | 769 def _load_template(self, name, globals): |
758 if self.loader is None: | 770 if self.loader is None: |
759 raise TypeError('no loader for this environment specified') | 771 raise TypeError('no loader for this environment specified') |
| 772 try: |
| 773 # use abs path for cache key |
| 774 cache_key = self.loader.get_source(self, name)[1] |
| 775 except RuntimeError: |
| 776 # if loader does not implement get_source() |
| 777 cache_key = None |
| 778 # if template is not file, use name for cache key |
| 779 if cache_key is None: |
| 780 cache_key = name |
760 if self.cache is not None: | 781 if self.cache is not None: |
761 template = self.cache.get(name) | 782 template = self.cache.get(cache_key) |
762 if template is not None and (not self.auto_reload or \ | 783 if template is not None and (not self.auto_reload or |
763 template.is_up_to_date): | 784 template.is_up_to_date): |
764 return template | 785 return template |
765 template = self.loader.load(self, name, globals) | 786 template = self.loader.load(self, name, globals) |
766 if self.cache is not None: | 787 if self.cache is not None: |
767 self.cache[name] = template | 788 self.cache[cache_key] = template |
768 return template | 789 return template |
769 | 790 |
770 @internalcode | 791 @internalcode |
771 def get_template(self, name, parent=None, globals=None): | 792 def get_template(self, name, parent=None, globals=None): |
772 """Load a template from the loader. If a loader is configured this | 793 """Load a template from the loader. If a loader is configured this |
773 method ask the loader for the template and returns a :class:`Template`. | 794 method ask the loader for the template and returns a :class:`Template`. |
774 If the `parent` parameter is not `None`, :meth:`join_path` is called | 795 If the `parent` parameter is not `None`, :meth:`join_path` is called |
775 to get the real template name before loading. | 796 to get the real template name before loading. |
776 | 797 |
777 The `globals` parameter can be used to provide template wide globals. | 798 The `globals` parameter can be used to provide template wide globals. |
(...skipping 81 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
859 Every template object has a few methods and members that are guaranteed | 880 Every template object has a few methods and members that are guaranteed |
860 to exist. However it's important that a template object should be | 881 to exist. However it's important that a template object should be |
861 considered immutable. Modifications on the object are not supported. | 882 considered immutable. Modifications on the object are not supported. |
862 | 883 |
863 Template objects created from the constructor rather than an environment | 884 Template objects created from the constructor rather than an environment |
864 do have an `environment` attribute that points to a temporary environment | 885 do have an `environment` attribute that points to a temporary environment |
865 that is probably shared with other templates created with the constructor | 886 that is probably shared with other templates created with the constructor |
866 and compatible settings. | 887 and compatible settings. |
867 | 888 |
868 >>> template = Template('Hello {{ name }}!') | 889 >>> template = Template('Hello {{ name }}!') |
869 >>> template.render(name='John Doe') | 890 >>> template.render(name='John Doe') == u'Hello John Doe!' |
870 u'Hello John Doe!' | 891 True |
871 | |
872 >>> stream = template.stream(name='John Doe') | 892 >>> stream = template.stream(name='John Doe') |
873 >>> stream.next() | 893 >>> next(stream) == u'Hello John Doe!' |
874 u'Hello John Doe!' | 894 True |
875 >>> stream.next() | 895 >>> next(stream) |
876 Traceback (most recent call last): | 896 Traceback (most recent call last): |
877 ... | 897 ... |
878 StopIteration | 898 StopIteration |
879 """ | 899 """ |
880 | 900 |
881 def __new__(cls, source, | 901 def __new__(cls, source, |
882 block_start_string=BLOCK_START_STRING, | 902 block_start_string=BLOCK_START_STRING, |
883 block_end_string=BLOCK_END_STRING, | 903 block_end_string=BLOCK_END_STRING, |
884 variable_start_string=VARIABLE_START_STRING, | 904 variable_start_string=VARIABLE_START_STRING, |
885 variable_end_string=VARIABLE_END_STRING, | 905 variable_end_string=VARIABLE_END_STRING, |
(...skipping 126 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1012 """ | 1032 """ |
1013 return TemplateModule(self, self.new_context(vars, shared, locals)) | 1033 return TemplateModule(self, self.new_context(vars, shared, locals)) |
1014 | 1034 |
1015 @property | 1035 @property |
1016 def module(self): | 1036 def module(self): |
1017 """The template as module. This is used for imports in the | 1037 """The template as module. This is used for imports in the |
1018 template runtime but is also useful if one wants to access | 1038 template runtime but is also useful if one wants to access |
1019 exported template variables from the Python layer: | 1039 exported template variables from the Python layer: |
1020 | 1040 |
1021 >>> t = Template('{% macro foo() %}42{% endmacro %}23') | 1041 >>> t = Template('{% macro foo() %}42{% endmacro %}23') |
1022 >>> unicode(t.module) | 1042 >>> str(t.module) |
1023 u'23' | 1043 '23' |
1024 >>> t.module.foo() | 1044 >>> t.module.foo() == u'42' |
1025 u'42' | 1045 True |
1026 """ | 1046 """ |
1027 if self._module is not None: | 1047 if self._module is not None: |
1028 return self._module | 1048 return self._module |
1029 self._module = rv = self.make_module() | 1049 self._module = rv = self.make_module() |
1030 return rv | 1050 return rv |
1031 | 1051 |
1032 def get_corresponding_lineno(self, lineno): | 1052 def get_corresponding_lineno(self, lineno): |
1033 """Return the source line number of a line number in the | 1053 """Return the source line number of a line number in the |
1034 generated bytecode as they are not in sync. | 1054 generated bytecode as they are not in sync. |
1035 """ | 1055 """ |
(...skipping 88 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1124 """Dump the complete stream into a file or file-like object. | 1144 """Dump the complete stream into a file or file-like object. |
1125 Per default unicode strings are written, if you want to encode | 1145 Per default unicode strings are written, if you want to encode |
1126 before writing specify an `encoding`. | 1146 before writing specify an `encoding`. |
1127 | 1147 |
1128 Example usage:: | 1148 Example usage:: |
1129 | 1149 |
1130 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') | 1150 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') |
1131 """ | 1151 """ |
1132 close = False | 1152 close = False |
1133 if isinstance(fp, string_types): | 1153 if isinstance(fp, string_types): |
1134 fp = open(fp, encoding is None and 'w' or 'wb') | 1154 if encoding is None: |
| 1155 encoding = 'utf-8' |
| 1156 fp = open(fp, 'wb') |
1135 close = True | 1157 close = True |
1136 try: | 1158 try: |
1137 if encoding is not None: | 1159 if encoding is not None: |
1138 iterable = (x.encode(encoding, errors) for x in self) | 1160 iterable = (x.encode(encoding, errors) for x in self) |
1139 else: | 1161 else: |
1140 iterable = self | 1162 iterable = self |
1141 if hasattr(fp, 'writelines'): | 1163 if hasattr(fp, 'writelines'): |
1142 fp.writelines(iterable) | 1164 fp.writelines(iterable) |
1143 else: | 1165 else: |
1144 for item in iterable: | 1166 for item in iterable: |
(...skipping 37 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
1182 def __iter__(self): | 1204 def __iter__(self): |
1183 return self | 1205 return self |
1184 | 1206 |
1185 def __next__(self): | 1207 def __next__(self): |
1186 return self._next() | 1208 return self._next() |
1187 | 1209 |
1188 | 1210 |
1189 # hook in default template class. if anyone reads this comment: ignore that | 1211 # hook in default template class. if anyone reads this comment: ignore that |
1190 # it's possible to use custom templates ;-) | 1212 # it's possible to use custom templates ;-) |
1191 Environment.template_class = Template | 1213 Environment.template_class = Template |
OLD | NEW |