| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | """ |
| Armin Ronacher | 82b3f3d | 2008-03-31 20:01:08 +0200 | [diff] [blame] | 3 | jinja2.environment |
| 4 | ~~~~~~~~~~~~~~~~~~ |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 5 | |
| 6 | Provides a class that holds runtime and parsing time options. |
| 7 | |
| Armin Ronacher | 55494e4 | 2010-01-22 09:41:48 +0100 | [diff] [blame] | 8 | :copyright: (c) 2010 by the Jinja Team. |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 9 | :license: BSD, see LICENSE for more details. |
| 10 | """ |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 11 | import os |
| Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 12 | import sys |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 13 | from jinja2 import nodes |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 14 | from jinja2.defaults import * |
| Armin Ronacher | 9a0078d | 2008-08-13 18:24:17 +0200 | [diff] [blame] | 15 | from jinja2.lexer import get_lexer, TokenStream |
| Armin Ronacher | 0553093 | 2008-04-20 13:27:49 +0200 | [diff] [blame] | 16 | from jinja2.parser import Parser |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 17 | from jinja2.optimizer import optimize |
| 18 | from jinja2.compiler import generate |
| Armin Ronacher | 74a0cd9 | 2009-02-19 15:56:53 +0100 | [diff] [blame] | 19 | from jinja2.runtime import Undefined, new_context |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 20 | from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \ |
| 21 | TemplatesNotFound |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 22 | from jinja2.utils import import_string, LRUCache, Markup, missing, \ |
| Armin Ronacher | 0d242be | 2010-02-10 01:35:13 +0100 | [diff] [blame] | 23 | concat, consume, internalcode, _encode_filename |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 24 | |
| 25 | |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 26 | # for direct template usage we have up to ten living environments |
| 27 | _spontaneous_environments = LRUCache(10) |
| 28 | |
| Armin Ronacher | a18872d | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 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 | |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 33 | |
| Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 34 | def get_spontaneous_environment(*args): |
| Georg Brandl | 3e497b7 | 2008-09-19 09:55:17 +0000 | [diff] [blame] | 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. |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 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) |
| Armin Ronacher | c9705c2 | 2008-04-27 21:28:03 +0200 | [diff] [blame] | 46 | env.shared = True |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 47 | return env |
| 48 | |
| 49 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 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 | |
| Armin Ronacher | ccae055 | 2008-10-05 23:08:58 +0200 | [diff] [blame] | 59 | def copy_cache(cache): |
| 60 | """Create an empty copy of the given cache.""" |
| 61 | if cache is None: |
| Armin Ronacher | 2bc1ef7 | 2008-12-08 15:21:26 +0100 | [diff] [blame] | 62 | return None |
| Armin Ronacher | ccae055 | 2008-10-05 23:08:58 +0200 | [diff] [blame] | 63 | elif type(cache) is dict: |
| 64 | return {} |
| 65 | return LRUCache(cache.capacity) |
| 66 | |
| 67 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 68 | def load_extensions(environment, extensions): |
| 69 | """Load the extensions from the list and bind it to the environment. |
| Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 70 | Returns a dict of instanciated environments. |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 71 | """ |
| Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 72 | result = {} |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 73 | for extension in extensions: |
| 74 | if isinstance(extension, basestring): |
| 75 | extension = import_string(extension) |
| Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 76 | result[extension.identifier] = extension(environment) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 77 | return result |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 78 | |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 79 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 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' |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 88 | assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ |
| 89 | 'newline_sequence set to unknown line ending string.' |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 90 | return environment |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 91 | |
| 92 | |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 93 | class Environment(object): |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 94 | r"""The core component of Jinja is the `Environment`. It contains |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 95 | important shared variables like configuration, filters, tests, |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 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 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 103 | `block_start_string` |
| 104 | The string marking the begin of a block. Defaults to ``'{%'``. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 105 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 106 | `block_end_string` |
| 107 | The string marking the end of a block. Defaults to ``'%}'``. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 108 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 109 | `variable_start_string` |
| 110 | The string marking the begin of a print statement. |
| 111 | Defaults to ``'{{'``. |
| Armin Ronacher | 115de2e | 2008-05-01 22:20:05 +0200 | [diff] [blame] | 112 | |
| Armin Ronacher | 63fd798 | 2008-06-20 18:47:56 +0200 | [diff] [blame] | 113 | `variable_end_string` |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 114 | The string marking the end of a print statement. Defaults to |
| 115 | ``'}}'``. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 116 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 117 | `comment_start_string` |
| 118 | The string marking the begin of a comment. Defaults to ``'{#'``. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 119 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 120 | `comment_end_string` |
| 121 | The string marking the end of a comment. Defaults to ``'#}'``. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 122 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 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`. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 126 | |
| Armin Ronacher | 59b6bd5 | 2009-03-30 21:00:16 +0200 | [diff] [blame] | 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 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 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`. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 136 | |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 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 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 143 | `extensions` |
| 144 | List of Jinja extensions to use. This can either be import paths |
| Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 145 | as strings or extension classes. For more information have a |
| 146 | look at :ref:`the extensions documentation <jinja-extensions>`. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 147 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 148 | `optimized` |
| 149 | should the optimizer be enabled? Default is `True`. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 150 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 151 | `undefined` |
| 152 | :class:`Undefined` or a subclass of it that is used to represent |
| 153 | undefined values in the template. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 154 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 155 | `finalize` |
| Armin Ronacher | d9ea26e | 2010-01-24 14:29:26 +0100 | [diff] [blame] | 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. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 159 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 160 | `autoescape` |
| Armin Ronacher | 8346bd7 | 2010-03-14 19:43:47 +0100 | [diff] [blame] | 161 | If set to true the XML/HTML autoescaping feature is enabled by |
| 162 | default. For more details about auto escaping see |
| Armin Ronacher | 1da23d1 | 2010-04-05 18:11:18 +0200 | [diff] [blame] | 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 |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 170 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 171 | `loader` |
| 172 | The template loader for this environment. |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 173 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 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. |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 180 | |
| Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 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. |
| Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 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. |
| Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 193 | |
| 194 | See :ref:`bytecode-cache` for more information. |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 195 | """ |
| 196 | |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 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 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 202 | #: True if the environment is just an overlay |
| Armin Ronacher | 619eeed | 2009-07-09 21:55:29 +0200 | [diff] [blame] | 203 | overlayed = False |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 204 | |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 205 | #: the environment this environment is linked to if it is an overlay |
| 206 | linked_to = None |
| 207 | |
| Armin Ronacher | c9705c2 | 2008-04-27 21:28:03 +0200 | [diff] [blame] | 208 | #: shared environments have this set to `True`. A shared environment |
| 209 | #: must not be modified |
| 210 | shared = False |
| 211 | |
| Armin Ronacher | 32ed6c9 | 2009-04-02 14:04:41 +0200 | [diff] [blame] | 212 | #: these are currently EXPERIMENTAL undocumented features. |
| Armin Ronacher | a18872d | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 213 | exception_handler = None |
| 214 | exception_formatter = None |
| 215 | |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 216 | def __init__(self, |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 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, |
| Armin Ronacher | 59b6bd5 | 2009-03-30 21:00:16 +0200 | [diff] [blame] | 224 | line_comment_prefix=LINE_COMMENT_PREFIX, |
| Armin Ronacher | 4f5008f | 2008-05-23 23:36:07 +0200 | [diff] [blame] | 225 | trim_blocks=TRIM_BLOCKS, |
| 226 | newline_sequence=NEWLINE_SEQUENCE, |
| Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 227 | extensions=(), |
| Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 228 | optimized=True, |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 229 | undefined=Undefined, |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 230 | finalize=None, |
| 231 | autoescape=False, |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 232 | loader=None, |
| 233 | cache_size=50, |
| Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 234 | auto_reload=True, |
| 235 | bytecode_cache=None): |
| Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 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 |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 245 | # existing already. |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 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 |
| Armin Ronacher | bf7c4ad | 2008-04-12 12:02:36 +0200 | [diff] [blame] | 254 | self.line_statement_prefix = line_statement_prefix |
| Armin Ronacher | 59b6bd5 | 2009-03-30 21:00:16 +0200 | [diff] [blame] | 255 | self.line_comment_prefix = line_comment_prefix |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 256 | self.trim_blocks = trim_blocks |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 257 | self.newline_sequence = newline_sequence |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 258 | |
| Armin Ronacher | f59bac2 | 2008-04-20 13:11:43 +0200 | [diff] [blame] | 259 | # runtime information |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 260 | self.undefined = undefined |
| Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 261 | self.optimized = optimized |
| Armin Ronacher | 18c6ca0 | 2008-04-17 10:03:29 +0200 | [diff] [blame] | 262 | self.finalize = finalize |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 263 | self.autoescape = autoescape |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 264 | |
| 265 | # defaults |
| 266 | self.filters = DEFAULT_FILTERS.copy() |
| 267 | self.tests = DEFAULT_TESTS.copy() |
| 268 | self.globals = DEFAULT_NAMESPACE.copy() |
| 269 | |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 270 | # set the loader provided |
| 271 | self.loader = loader |
| Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 272 | self.bytecode_cache = None |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 273 | self.cache = create_cache(cache_size) |
| Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 274 | self.bytecode_cache = bytecode_cache |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 275 | self.auto_reload = auto_reload |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 276 | |
| Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 277 | # load extensions |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 278 | self.extensions = load_extensions(self, extensions) |
| 279 | |
| 280 | _environment_sanity_check(self) |
| 281 | |
| Armin Ronacher | b8892e7 | 2010-05-29 17:58:06 +0200 | [diff] [blame^] | 282 | def add_extension(self, extension): |
| 283 | """Adds an extension after the environment was created. |
| 284 | |
| 285 | .. versionadded:: 2.5 |
| 286 | """ |
| 287 | load_extensions(self, [extension]) |
| 288 | |
| Armin Ronacher | 762079c | 2008-05-08 23:57:56 +0200 | [diff] [blame] | 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 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 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, |
| Armin Ronacher | 59b6bd5 | 2009-03-30 21:00:16 +0200 | [diff] [blame] | 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, |
| Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 305 | bytecode_cache=missing): |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 306 | """Create a new overlay environment that shares all the data with the |
| Georg Brandl | 95632c4 | 2009-11-22 18:35:18 +0100 | [diff] [blame] | 307 | current environment except of cache and the overridden attributes. |
| 308 | Extensions cannot be removed for an overlayed environment. An overlayed |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 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__) |
| Armin Ronacher | 619eeed | 2009-07-09 21:55:29 +0200 | [diff] [blame] | 322 | rv.overlayed = True |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 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) |
| Armin Ronacher | ccae055 | 2008-10-05 23:08:58 +0200 | [diff] [blame] | 331 | else: |
| 332 | rv.cache = copy_cache(self.cache) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 333 | |
| Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 334 | rv.extensions = {} |
| 335 | for key, value in self.extensions.iteritems(): |
| 336 | rv.extensions[key] = value.bind(rv) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 337 | if extensions is not missing: |
| Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 338 | rv.extensions.update(load_extensions(extensions)) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 339 | |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 340 | return _environment_sanity_check(rv) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 341 | |
| Armin Ronacher | 9a0078d | 2008-08-13 18:24:17 +0200 | [diff] [blame] | 342 | lexer = property(get_lexer, doc="The lexer for this environment.") |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 343 | |
| Armin Ronacher | 5b3f4dc | 2010-04-12 14:04:14 +0200 | [diff] [blame] | 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 | |
| Armin Ronacher | 6dc6f29 | 2008-06-12 08:50:07 +0200 | [diff] [blame] | 349 | def getitem(self, obj, argument): |
| 350 | """Get an item or attribute of an object but prefer the item.""" |
| Armin Ronacher | 08a6a3b | 2008-05-13 15:35:47 +0200 | [diff] [blame] | 351 | try: |
| 352 | return obj[argument] |
| 353 | except (TypeError, LookupError): |
| Armin Ronacher | f15f5f7 | 2008-05-26 12:21:45 +0200 | [diff] [blame] | 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 |
| Armin Ronacher | 08a6a3b | 2008-05-13 15:35:47 +0200 | [diff] [blame] | 364 | return self.undefined(obj=obj, name=argument) |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 365 | |
| Armin Ronacher | 6dc6f29 | 2008-06-12 08:50:07 +0200 | [diff] [blame] | 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] |
| Christopher Grebs | f1c940f | 2008-07-10 11:52:17 +0200 | [diff] [blame] | 376 | except (TypeError, LookupError, AttributeError): |
| Armin Ronacher | 6dc6f29 | 2008-06-12 08:50:07 +0200 | [diff] [blame] | 377 | return self.undefined(obj=obj, name=attribute) |
| 378 | |
| Armin Ronacher | d416a97 | 2009-02-24 22:58:00 +0100 | [diff] [blame] | 379 | @internalcode |
| Armin Ronacher | 7f15ef8 | 2008-05-16 09:11:39 +0200 | [diff] [blame] | 380 | def parse(self, source, name=None, filename=None): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 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. |
| Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 385 | |
| 386 | If you are :ref:`developing Jinja2 extensions <writing-extensions>` |
| 387 | this gives you a good overview of the node tree generated. |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 388 | """ |
| Armin Ronacher | aaf010d | 2008-05-01 13:14:30 +0200 | [diff] [blame] | 389 | try: |
| Armin Ronacher | efcc0e5 | 2009-09-13 00:22:50 -0700 | [diff] [blame] | 390 | return self._parse(source, name, filename) |
| Armin Ronacher | 2a79192 | 2009-04-16 23:15:22 +0200 | [diff] [blame] | 391 | except TemplateSyntaxError: |
| Armin Ronacher | bd35772 | 2009-08-05 20:25:06 +0200 | [diff] [blame] | 392 | exc_info = sys.exc_info() |
| 393 | self.handle_exception(exc_info, source_hint=source) |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 394 | |
| Armin Ronacher | efcc0e5 | 2009-09-13 00:22:50 -0700 | [diff] [blame] | 395 | def _parse(self, source, name, filename): |
| 396 | """Internal parsing function used by `parse` and `compile`.""" |
| Armin Ronacher | 0d242be | 2010-02-10 01:35:13 +0100 | [diff] [blame] | 397 | return Parser(self, source, name, _encode_filename(filename)).parse() |
| Armin Ronacher | efcc0e5 | 2009-09-13 00:22:50 -0700 | [diff] [blame] | 398 | |
| Armin Ronacher | 7f15ef8 | 2008-05-16 09:11:39 +0200 | [diff] [blame] | 399 | def lex(self, source, name=None, filename=None): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 400 | """Lex the given sourcecode and return a generator that yields |
| 401 | tokens as tuples in the form ``(lineno, token_type, value)``. |
| Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 402 | This can be useful for :ref:`extension development <writing-extensions>` |
| 403 | and debugging templates. |
| Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 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. |
| Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 408 | """ |
| Armin Ronacher | ccae055 | 2008-10-05 23:08:58 +0200 | [diff] [blame] | 409 | source = unicode(source) |
| 410 | try: |
| 411 | return self.lexer.tokeniter(source, name, filename) |
| Armin Ronacher | 2a79192 | 2009-04-16 23:15:22 +0200 | [diff] [blame] | 412 | except TemplateSyntaxError: |
| Armin Ronacher | bd35772 | 2009-08-05 20:25:06 +0200 | [diff] [blame] | 413 | exc_info = sys.exc_info() |
| 414 | self.handle_exception(exc_info, source_hint=source) |
| Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 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), |
| Armin Ronacher | 5b3f4dc | 2010-04-12 14:04:14 +0200 | [diff] [blame] | 422 | self.iter_extensions(), unicode(source)) |
| Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 423 | |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 424 | def _tokenize(self, source, name, filename=None, state=None): |
| Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 425 | """Called by the parser to do the preprocessing and filtering |
| 426 | for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. |
| 427 | """ |
| Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 428 | source = self.preprocess(source, name, filename) |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 429 | stream = self.lexer.tokenize(source, name, filename, state) |
| Armin Ronacher | 5b3f4dc | 2010-04-12 14:04:14 +0200 | [diff] [blame] | 430 | for ext in self.iter_extensions(): |
| Armin Ronacher | 3e3a9be | 2008-06-14 12:44:15 +0200 | [diff] [blame] | 431 | stream = ext.filter_stream(stream) |
| 432 | if not isinstance(stream, TokenStream): |
| 433 | stream = TokenStream(stream, name, filename) |
| Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 434 | return stream |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 435 | |
| Armin Ronacher | d416a97 | 2009-02-24 22:58:00 +0100 | [diff] [blame] | 436 | @internalcode |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 437 | def compile(self, source, name=None, filename=None, raw=False, |
| 438 | defer_init=False): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 439 | """Compile a node or template source code. The `name` parameter is |
| 440 | the load name of the template after it was joined using |
| 441 | :meth:`join_path` if necessary, not the filename on the file system. |
| 442 | the `filename` parameter is the estimated filename of the template on |
| 443 | the file system. If the template came from a database or memory this |
| Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 444 | can be omitted. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 445 | |
| 446 | The return value of this method is a python code object. If the `raw` |
| 447 | parameter is `True` the return value will be a string with python |
| 448 | code equivalent to the bytecode returned otherwise. This method is |
| 449 | mainly used internally. |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 450 | |
| 451 | `defer_init` is use internally to aid the module code generator. This |
| 452 | causes the generated code to be able to import without the global |
| 453 | environment variable to be set. |
| 454 | |
| 455 | .. versionadded:: 2.4 |
| 456 | `defer_init` parameter added. |
| Armin Ronacher | 68f7767 | 2008-04-17 11:50:39 +0200 | [diff] [blame] | 457 | """ |
| Armin Ronacher | efcc0e5 | 2009-09-13 00:22:50 -0700 | [diff] [blame] | 458 | source_hint = None |
| 459 | try: |
| 460 | if isinstance(source, basestring): |
| 461 | source_hint = source |
| 462 | source = self._parse(source, name, filename) |
| 463 | if self.optimized: |
| 464 | source = optimize(source, self) |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 465 | source = generate(source, self, name, filename, |
| 466 | defer_init=defer_init) |
| Armin Ronacher | efcc0e5 | 2009-09-13 00:22:50 -0700 | [diff] [blame] | 467 | if raw: |
| 468 | return source |
| 469 | if filename is None: |
| 470 | filename = '<template>' |
| Armin Ronacher | 0d242be | 2010-02-10 01:35:13 +0100 | [diff] [blame] | 471 | else: |
| 472 | filename = _encode_filename(filename) |
| Armin Ronacher | efcc0e5 | 2009-09-13 00:22:50 -0700 | [diff] [blame] | 473 | return compile(source, filename, 'exec') |
| 474 | except TemplateSyntaxError: |
| 475 | exc_info = sys.exc_info() |
| 476 | self.handle_exception(exc_info, source_hint=source) |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 477 | |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 478 | def compile_expression(self, source, undefined_to_none=True): |
| 479 | """A handy helper method that returns a callable that accepts keyword |
| 480 | arguments that appear as variables in the expression. If called it |
| 481 | returns the result of the expression. |
| 482 | |
| 483 | This is useful if applications want to use the same rules as Jinja |
| 484 | in template "configuration files" or similar situations. |
| 485 | |
| 486 | Example usage: |
| 487 | |
| 488 | >>> env = Environment() |
| 489 | >>> expr = env.compile_expression('foo == 42') |
| 490 | >>> expr(foo=23) |
| 491 | False |
| 492 | >>> expr(foo=42) |
| 493 | True |
| 494 | |
| 495 | Per default the return value is converted to `None` if the |
| 496 | expression returns an undefined value. This can be changed |
| 497 | by setting `undefined_to_none` to `False`. |
| 498 | |
| 499 | >>> env.compile_expression('var')() is None |
| 500 | True |
| 501 | >>> env.compile_expression('var', undefined_to_none=False)() |
| 502 | Undefined |
| 503 | |
| Armin Ronacher | 0319c66 | 2010-02-09 02:09:10 +0100 | [diff] [blame] | 504 | .. versionadded:: 2.1 |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 505 | """ |
| 506 | parser = Parser(self, source, state='variable') |
| Armin Ronacher | bd35772 | 2009-08-05 20:25:06 +0200 | [diff] [blame] | 507 | exc_info = None |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 508 | try: |
| 509 | expr = parser.parse_expression() |
| 510 | if not parser.stream.eos: |
| 511 | raise TemplateSyntaxError('chunk after expression', |
| 512 | parser.stream.current.lineno, |
| 513 | None, None) |
| Armin Ronacher | 8346bd7 | 2010-03-14 19:43:47 +0100 | [diff] [blame] | 514 | expr.set_environment(self) |
| Armin Ronacher | 2a79192 | 2009-04-16 23:15:22 +0200 | [diff] [blame] | 515 | except TemplateSyntaxError: |
| Armin Ronacher | bd35772 | 2009-08-05 20:25:06 +0200 | [diff] [blame] | 516 | exc_info = sys.exc_info() |
| 517 | if exc_info is not None: |
| 518 | self.handle_exception(exc_info, source_hint=source) |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 519 | body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)] |
| 520 | template = self.from_string(nodes.Template(body, lineno=1)) |
| 521 | return TemplateExpression(template, undefined_to_none) |
| 522 | |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 523 | def compile_templates(self, target, extensions=None, filter_func=None, |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 524 | zip='deflated', log_function=None, |
| 525 | ignore_errors=True, py_compile=False): |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 526 | """Compiles all the templates the loader can find, compiles them |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 527 | and stores them in `target`. If `zip` is `None`, instead of in a |
| 528 | zipfile, the templates will be will be stored in a directory. |
| 529 | By default a deflate zip algorithm is used, to switch to |
| 530 | the stored algorithm, `zip` can be set to ``'stored'``. |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 531 | |
| 532 | `extensions` and `filter_func` are passed to :meth:`list_templates`. |
| 533 | Each template returned will be compiled to the target folder or |
| 534 | zipfile. |
| 535 | |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 536 | By default template compilation errors are ignored. In case a |
| 537 | log function is provided, errors are logged. If you want template |
| 538 | syntax errors to abort the compilation you can set `ignore_errors` |
| 539 | to `False` and you will get an exception on syntax errors. |
| 540 | |
| 541 | If `py_compile` is set to `True` .pyc files will be written to the |
| 542 | target instead of standard .py files. |
| 543 | |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 544 | .. versionadded:: 2.4 |
| 545 | """ |
| 546 | from jinja2.loaders import ModuleLoader |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 547 | |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 548 | if log_function is None: |
| 549 | log_function = lambda x: None |
| 550 | |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 551 | if py_compile: |
| 552 | import imp, struct, marshal |
| Armin Ronacher | c57959d | 2010-03-15 00:54:01 +0100 | [diff] [blame] | 553 | py_header = imp.get_magic() + \ |
| 554 | u'\xff\xff\xff\xff'.encode('iso-8859-15') |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 555 | |
| Armin Ronacher | c57959d | 2010-03-15 00:54:01 +0100 | [diff] [blame] | 556 | def write_file(filename, data, mode): |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 557 | if zip: |
| 558 | info = ZipInfo(filename) |
| 559 | info.external_attr = 0755 << 16L |
| 560 | zip_file.writestr(info, data) |
| 561 | else: |
| Armin Ronacher | c57959d | 2010-03-15 00:54:01 +0100 | [diff] [blame] | 562 | f = open(os.path.join(target, filename), mode) |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 563 | try: |
| 564 | f.write(data) |
| 565 | finally: |
| 566 | f.close() |
| 567 | |
| 568 | if zip is not None: |
| 569 | from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED |
| 570 | zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED, |
| 571 | stored=ZIP_STORED)[zip]) |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 572 | log_function('Compiling into Zip archive "%s"' % target) |
| 573 | else: |
| 574 | if not os.path.isdir(target): |
| 575 | os.makedirs(target) |
| 576 | log_function('Compiling into folder "%s"' % target) |
| 577 | |
| 578 | try: |
| 579 | for name in self.list_templates(extensions, filter_func): |
| 580 | source, filename, _ = self.loader.get_source(self, name) |
| 581 | try: |
| 582 | code = self.compile(source, name, filename, True, True) |
| 583 | except TemplateSyntaxError, e: |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 584 | if not ignore_errors: |
| 585 | raise |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 586 | log_function('Could not compile "%s": %s' % (name, e)) |
| 587 | continue |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 588 | |
| 589 | filename = ModuleLoader.get_module_filename(name) |
| 590 | |
| 591 | if py_compile: |
| 592 | c = compile(code, _encode_filename(filename), 'exec') |
| Armin Ronacher | c57959d | 2010-03-15 00:54:01 +0100 | [diff] [blame] | 593 | write_file(filename + 'c', py_header + |
| 594 | marshal.dumps(c), 'wb') |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 595 | log_function('Byte-compiled "%s" as %s' % |
| 596 | (name, filename + 'c')) |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 597 | else: |
| Armin Ronacher | c57959d | 2010-03-15 00:54:01 +0100 | [diff] [blame] | 598 | write_file(filename, code, 'w') |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 599 | log_function('Compiled "%s" as %s' % (name, filename)) |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 600 | finally: |
| 601 | if zip: |
| Armin Ronacher | 12a316b | 2010-03-12 17:59:51 +0100 | [diff] [blame] | 602 | zip_file.close() |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 603 | |
| 604 | log_function('Finished compiling templates') |
| 605 | |
| 606 | def list_templates(self, extensions=None, filter_func=None): |
| 607 | """Returns a list of templates for this environment. This requires |
| 608 | that the loader supports the loader's |
| 609 | :meth:`~BaseLoader.list_templates` method. |
| 610 | |
| 611 | If there are other files in the template folder besides the |
| 612 | actual templates, the returned list can be filtered. There are two |
| 613 | ways: either `extensions` is set to a list of file extensions for |
| 614 | templates, or a `filter_func` can be provided which is a callable that |
| 615 | is passed a template name and should return `True` if it should end up |
| 616 | in the result list. |
| 617 | |
| 618 | If the loader does not support that, a :exc:`TypeError` is raised. |
| 619 | """ |
| 620 | x = self.loader.list_templates() |
| 621 | if extensions is not None: |
| 622 | if filter_func is not None: |
| 623 | raise TypeError('either extensions or filter_func ' |
| 624 | 'can be passed, but not both') |
| 625 | filter_func = lambda x: '.' in x and \ |
| 626 | x.rsplit('.', 1)[1] in extensions |
| 627 | if filter_func is not None: |
| 628 | x = filter(filter_func, x) |
| 629 | return x |
| 630 | |
| Armin Ronacher | a18872d | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 631 | def handle_exception(self, exc_info=None, rendered=False, source_hint=None): |
| 632 | """Exception handling helper. This is used internally to either raise |
| 633 | rewritten exceptions or return a rendered traceback for the template. |
| 634 | """ |
| 635 | global _make_traceback |
| 636 | if exc_info is None: |
| 637 | exc_info = sys.exc_info() |
| Armin Ronacher | 32ed6c9 | 2009-04-02 14:04:41 +0200 | [diff] [blame] | 638 | |
| 639 | # the debugging module is imported when it's used for the first time. |
| 640 | # we're doing a lot of stuff there and for applications that do not |
| 641 | # get any exceptions in template rendering there is no need to load |
| 642 | # all of that. |
| Armin Ronacher | a18872d | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 643 | if _make_traceback is None: |
| 644 | from jinja2.debug import make_traceback as _make_traceback |
| 645 | traceback = _make_traceback(exc_info, source_hint) |
| 646 | if rendered and self.exception_formatter is not None: |
| 647 | return self.exception_formatter(traceback) |
| 648 | if self.exception_handler is not None: |
| 649 | self.exception_handler(traceback) |
| 650 | exc_type, exc_value, tb = traceback.standard_exc_info |
| 651 | raise exc_type, exc_value, tb |
| 652 | |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 653 | def join_path(self, template, parent): |
| 654 | """Join a template with the parent. By default all the lookups are |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 655 | relative to the loader root so this method returns the `template` |
| 656 | parameter unchanged, but if the paths should be relative to the |
| 657 | parent template, this function can be used to calculate the real |
| 658 | template name. |
| 659 | |
| 660 | Subclasses may override this method and implement template path |
| 661 | joining here. |
| 662 | """ |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 663 | return template |
| 664 | |
| Armin Ronacher | d416a97 | 2009-02-24 22:58:00 +0100 | [diff] [blame] | 665 | @internalcode |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 666 | def _load_template(self, name, globals): |
| 667 | if self.loader is None: |
| 668 | raise TypeError('no loader for this environment specified') |
| 669 | if self.cache is not None: |
| 670 | template = self.cache.get(name) |
| 671 | if template is not None and (not self.auto_reload or \ |
| 672 | template.is_up_to_date): |
| 673 | return template |
| 674 | template = self.loader.load(self, name, globals) |
| 675 | if self.cache is not None: |
| 676 | self.cache[name] = template |
| 677 | return template |
| 678 | |
| 679 | @internalcode |
| Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 680 | def get_template(self, name, parent=None, globals=None): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 681 | """Load a template from the loader. If a loader is configured this |
| 682 | method ask the loader for the template and returns a :class:`Template`. |
| 683 | If the `parent` parameter is not `None`, :meth:`join_path` is called |
| 684 | to get the real template name before loading. |
| 685 | |
| Armin Ronacher | 7a519ee | 2008-09-08 23:10:47 +0200 | [diff] [blame] | 686 | The `globals` parameter can be used to provide template wide globals. |
| Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 687 | These variables are available in the context at render time. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 688 | |
| 689 | If the template does not exist a :exc:`TemplateNotFound` exception is |
| 690 | raised. |
| Armin Ronacher | c2c6351 | 2010-02-16 17:37:17 +0100 | [diff] [blame] | 691 | |
| 692 | .. versionchanged:: 2.4 |
| 693 | If `name` is a :class:`Template` object it is returned from the |
| 694 | function unchanged. |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 695 | """ |
| Armin Ronacher | 9165d3e | 2010-02-16 17:35:59 +0100 | [diff] [blame] | 696 | if isinstance(name, Template): |
| 697 | return name |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 698 | if parent is not None: |
| 699 | name = self.join_path(name, parent) |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 700 | return self._load_template(name, self.make_globals(globals)) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 701 | |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 702 | @internalcode |
| 703 | def select_template(self, names, parent=None, globals=None): |
| 704 | """Works like :meth:`get_template` but tries a number of templates |
| 705 | before it fails. If it cannot find any of the templates, it will |
| 706 | raise a :exc:`TemplatesNotFound` exception. |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 707 | |
| Armin Ronacher | 0319c66 | 2010-02-09 02:09:10 +0100 | [diff] [blame] | 708 | .. versionadded:: 2.3 |
| Armin Ronacher | c2c6351 | 2010-02-16 17:37:17 +0100 | [diff] [blame] | 709 | |
| 710 | .. versionchanged:: 2.4 |
| 711 | If `names` contains a :class:`Template` object it is returned |
| 712 | from the function unchanged. |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 713 | """ |
| 714 | if not names: |
| 715 | raise TemplatesNotFound(message=u'Tried to select from an empty list ' |
| 716 | u'of templates.') |
| 717 | globals = self.make_globals(globals) |
| 718 | for name in names: |
| Armin Ronacher | 9165d3e | 2010-02-16 17:35:59 +0100 | [diff] [blame] | 719 | if isinstance(name, Template): |
| 720 | return name |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 721 | if parent is not None: |
| 722 | name = self.join_path(name, parent) |
| 723 | try: |
| 724 | return self._load_template(name, globals) |
| 725 | except TemplateNotFound: |
| 726 | pass |
| 727 | raise TemplatesNotFound(names) |
| 728 | |
| 729 | @internalcode |
| 730 | def get_or_select_template(self, template_name_or_list, |
| 731 | parent=None, globals=None): |
| Armin Ronacher | 0430679 | 2010-02-17 00:16:07 +0100 | [diff] [blame] | 732 | """Does a typecheck and dispatches to :meth:`select_template` |
| 733 | if an iterable of template names is given, otherwise to |
| 734 | :meth:`get_template`. |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 735 | |
| Armin Ronacher | 0319c66 | 2010-02-09 02:09:10 +0100 | [diff] [blame] | 736 | .. versionadded:: 2.3 |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 737 | """ |
| 738 | if isinstance(template_name_or_list, basestring): |
| 739 | return self.get_template(template_name_or_list, parent, globals) |
| Armin Ronacher | 9165d3e | 2010-02-16 17:35:59 +0100 | [diff] [blame] | 740 | elif isinstance(template_name_or_list, Template): |
| 741 | return template_name_or_list |
| Armin Ronacher | 31bbd9e | 2010-01-14 00:41:30 +0100 | [diff] [blame] | 742 | return self.select_template(template_name_or_list, parent, globals) |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 743 | |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 744 | def from_string(self, source, globals=None, template_class=None): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 745 | """Load a template from a string. This parses the source given and |
| 746 | returns a :class:`Template` object. |
| 747 | """ |
| Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 748 | globals = self.make_globals(globals) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 749 | cls = template_class or self.template_class |
| Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 750 | return cls.from_code(self, self.compile(source), globals, None) |
| Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 751 | |
| 752 | def make_globals(self, d): |
| 753 | """Return a dict for the globals.""" |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 754 | if not d: |
| Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 755 | return self.globals |
| 756 | return dict(self.globals, **d) |
| Armin Ronacher | 46f5f98 | 2008-04-11 16:40:09 +0200 | [diff] [blame] | 757 | |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 758 | |
| 759 | class Template(object): |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 760 | """The central template object. This class represents a compiled template |
| 761 | and is used to evaluate it. |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 762 | |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 763 | Normally the template object is generated from an :class:`Environment` but |
| 764 | it also has a constructor that makes it possible to create a template |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 765 | instance directly using the constructor. It takes the same arguments as |
| 766 | the environment constructor but it's not possible to specify a loader. |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 767 | |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 768 | Every template object has a few methods and members that are guaranteed |
| 769 | to exist. However it's important that a template object should be |
| 770 | considered immutable. Modifications on the object are not supported. |
| 771 | |
| 772 | Template objects created from the constructor rather than an environment |
| 773 | do have an `environment` attribute that points to a temporary environment |
| 774 | that is probably shared with other templates created with the constructor |
| 775 | and compatible settings. |
| 776 | |
| 777 | >>> template = Template('Hello {{ name }}!') |
| 778 | >>> template.render(name='John Doe') |
| 779 | u'Hello John Doe!' |
| 780 | |
| 781 | >>> stream = template.stream(name='John Doe') |
| 782 | >>> stream.next() |
| 783 | u'Hello John Doe!' |
| 784 | >>> stream.next() |
| 785 | Traceback (most recent call last): |
| 786 | ... |
| 787 | StopIteration |
| 788 | """ |
| 789 | |
| 790 | def __new__(cls, source, |
| Armin Ronacher | 4f5008f | 2008-05-23 23:36:07 +0200 | [diff] [blame] | 791 | block_start_string=BLOCK_START_STRING, |
| 792 | block_end_string=BLOCK_END_STRING, |
| 793 | variable_start_string=VARIABLE_START_STRING, |
| 794 | variable_end_string=VARIABLE_END_STRING, |
| 795 | comment_start_string=COMMENT_START_STRING, |
| 796 | comment_end_string=COMMENT_END_STRING, |
| 797 | line_statement_prefix=LINE_STATEMENT_PREFIX, |
| Armin Ronacher | 59b6bd5 | 2009-03-30 21:00:16 +0200 | [diff] [blame] | 798 | line_comment_prefix=LINE_COMMENT_PREFIX, |
| Armin Ronacher | 4f5008f | 2008-05-23 23:36:07 +0200 | [diff] [blame] | 799 | trim_blocks=TRIM_BLOCKS, |
| 800 | newline_sequence=NEWLINE_SEQUENCE, |
| Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 801 | extensions=(), |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 802 | optimized=True, |
| 803 | undefined=Undefined, |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 804 | finalize=None, |
| 805 | autoescape=False): |
| Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 806 | env = get_spontaneous_environment( |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 807 | block_start_string, block_end_string, variable_start_string, |
| 808 | variable_end_string, comment_start_string, comment_end_string, |
| Armin Ronacher | 59b6bd5 | 2009-03-30 21:00:16 +0200 | [diff] [blame] | 809 | line_statement_prefix, line_comment_prefix, trim_blocks, |
| 810 | newline_sequence, frozenset(extensions), optimized, undefined, |
| 811 | finalize, autoescape, None, 0, False, None) |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 812 | return env.from_string(source, template_class=cls) |
| Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 813 | |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 814 | @classmethod |
| 815 | def from_code(cls, environment, code, globals, uptodate=None): |
| 816 | """Creates a template object from compiled code and the globals. This |
| 817 | is used by the loaders and environment to create a template object. |
| 818 | """ |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 819 | namespace = { |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 820 | 'environment': environment, |
| 821 | '__file__': code.co_filename |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 822 | } |
| 823 | exec code in namespace |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 824 | rv = cls._from_namespace(environment, namespace, globals) |
| 825 | rv._uptodate = uptodate |
| 826 | return rv |
| 827 | |
| 828 | @classmethod |
| 829 | def from_module_dict(cls, environment, module_dict, globals): |
| 830 | """Creates a template object from a module. This is used by the |
| 831 | module loader to create a template object. |
| 832 | |
| 833 | .. versionadded:: 2.4 |
| 834 | """ |
| 835 | return cls._from_namespace(environment, module_dict, globals) |
| 836 | |
| 837 | @classmethod |
| 838 | def _from_namespace(cls, environment, namespace, globals): |
| 839 | t = object.__new__(cls) |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 840 | t.environment = environment |
| Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 841 | t.globals = globals |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 842 | t.name = namespace['name'] |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 843 | t.filename = namespace['__file__'] |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 844 | t.blocks = namespace['blocks'] |
| Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 845 | |
| Georg Brandl | 3e497b7 | 2008-09-19 09:55:17 +0000 | [diff] [blame] | 846 | # render function and module |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 847 | t.root_render_func = namespace['root'] |
| Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 848 | t._module = None |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 849 | |
| 850 | # debug and loader helpers |
| 851 | t._debug_info = namespace['debug_info'] |
| Armin Ronacher | 64b08a0 | 2010-03-12 03:17:41 +0100 | [diff] [blame] | 852 | t._uptodate = None |
| 853 | |
| 854 | # store the reference |
| 855 | namespace['environment'] = environment |
| 856 | namespace['__jinja_template__'] = t |
| Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 857 | |
| 858 | return t |
| 859 | |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 860 | def render(self, *args, **kwargs): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 861 | """This method accepts the same arguments as the `dict` constructor: |
| 862 | A dict, a dict subclass or some keyword arguments. If no arguments |
| 863 | are given the context will be empty. These two calls do the same:: |
| 864 | |
| 865 | template.render(knights='that say nih') |
| 866 | template.render({'knights': 'that say nih'}) |
| 867 | |
| 868 | This will return the rendered template as unicode string. |
| 869 | """ |
| Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 870 | vars = dict(*args, **kwargs) |
| Armin Ronacher | f41d139 | 2008-04-18 16:41:52 +0200 | [diff] [blame] | 871 | try: |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 872 | return concat(self.root_render_func(self.new_context(vars))) |
| Armin Ronacher | f41d139 | 2008-04-18 16:41:52 +0200 | [diff] [blame] | 873 | except: |
| Armin Ronacher | bd35772 | 2009-08-05 20:25:06 +0200 | [diff] [blame] | 874 | exc_info = sys.exc_info() |
| 875 | return self.environment.handle_exception(exc_info, True) |
| Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 876 | |
| 877 | def stream(self, *args, **kwargs): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 878 | """Works exactly like :meth:`generate` but returns a |
| 879 | :class:`TemplateStream`. |
| 880 | """ |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 881 | return TemplateStream(self.generate(*args, **kwargs)) |
| Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 882 | |
| 883 | def generate(self, *args, **kwargs): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 884 | """For very large templates it can be useful to not render the whole |
| 885 | template at once but evaluate each statement after another and yield |
| 886 | piece for piece. This method basically does exactly that and returns |
| 887 | a generator that yields one item after another as unicode strings. |
| 888 | |
| 889 | It accepts the same arguments as :meth:`render`. |
| 890 | """ |
| Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 891 | vars = dict(*args, **kwargs) |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 892 | try: |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 893 | for event in self.root_render_func(self.new_context(vars)): |
| Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 894 | yield event |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 895 | except: |
| Armin Ronacher | bd35772 | 2009-08-05 20:25:06 +0200 | [diff] [blame] | 896 | exc_info = sys.exc_info() |
| 897 | else: |
| 898 | return |
| 899 | yield self.environment.handle_exception(exc_info, True) |
| Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 900 | |
| Armin Ronacher | 673aa88 | 2008-10-04 18:06:57 +0200 | [diff] [blame] | 901 | def new_context(self, vars=None, shared=False, locals=None): |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 902 | """Create a new :class:`Context` for this template. The vars |
| Armin Ronacher | c9705c2 | 2008-04-27 21:28:03 +0200 | [diff] [blame] | 903 | provided will be passed to the template. Per default the globals |
| Armin Ronacher | 673aa88 | 2008-10-04 18:06:57 +0200 | [diff] [blame] | 904 | are added to the context. If shared is set to `True` the data |
| 905 | is passed as it to the context without adding the globals. |
| 906 | |
| 907 | `locals` can be a dict of local variables for internal usage. |
| Armin Ronacher | c9705c2 | 2008-04-27 21:28:03 +0200 | [diff] [blame] | 908 | """ |
| Armin Ronacher | 74a0cd9 | 2009-02-19 15:56:53 +0100 | [diff] [blame] | 909 | return new_context(self.environment, self.name, self.blocks, |
| 910 | vars, shared, self.globals, locals) |
| Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 911 | |
| Armin Ronacher | 673aa88 | 2008-10-04 18:06:57 +0200 | [diff] [blame] | 912 | def make_module(self, vars=None, shared=False, locals=None): |
| Armin Ronacher | 7ceced5 | 2008-05-03 10:15:31 +0200 | [diff] [blame] | 913 | """This method works like the :attr:`module` attribute when called |
| Armin Ronacher | 0aa0f58 | 2009-03-18 01:01:36 +0100 | [diff] [blame] | 914 | without arguments but it will evaluate the template on every call |
| 915 | rather than caching it. It's also possible to provide |
| Armin Ronacher | 7ceced5 | 2008-05-03 10:15:31 +0200 | [diff] [blame] | 916 | a dict which is then used as context. The arguments are the same |
| Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 917 | as for the :meth:`new_context` method. |
| Armin Ronacher | ea847c5 | 2008-05-02 20:04:32 +0200 | [diff] [blame] | 918 | """ |
| Armin Ronacher | 673aa88 | 2008-10-04 18:06:57 +0200 | [diff] [blame] | 919 | return TemplateModule(self, self.new_context(vars, shared, locals)) |
| Armin Ronacher | ea847c5 | 2008-05-02 20:04:32 +0200 | [diff] [blame] | 920 | |
| Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 921 | @property |
| 922 | def module(self): |
| 923 | """The template as module. This is used for imports in the |
| 924 | template runtime but is also useful if one wants to access |
| 925 | exported template variables from the Python layer: |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 926 | |
| Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 927 | >>> t = Template('{% macro foo() %}42{% endmacro %}23') |
| 928 | >>> unicode(t.module) |
| 929 | u'23' |
| 930 | >>> t.module.foo() |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 931 | u'42' |
| Armin Ronacher | 6ce170c | 2008-04-25 12:32:36 +0200 | [diff] [blame] | 932 | """ |
| Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 933 | if self._module is not None: |
| Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 934 | return self._module |
| Armin Ronacher | ea847c5 | 2008-05-02 20:04:32 +0200 | [diff] [blame] | 935 | self._module = rv = self.make_module() |
| Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 936 | return rv |
| Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 937 | |
| Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 938 | def get_corresponding_lineno(self, lineno): |
| 939 | """Return the source line number of a line number in the |
| 940 | generated bytecode as they are not in sync. |
| 941 | """ |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 942 | for template_line, code_line in reversed(self.debug_info): |
| Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 943 | if code_line <= lineno: |
| 944 | return template_line |
| 945 | return 1 |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 946 | |
| Armin Ronacher | 9a82205 | 2008-04-17 18:44:07 +0200 | [diff] [blame] | 947 | @property |
| Armin Ronacher | 814f6c2 | 2008-04-17 15:52:23 +0200 | [diff] [blame] | 948 | def is_up_to_date(self): |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 949 | """If this variable is `False` there is a newer version available.""" |
| Armin Ronacher | 814f6c2 | 2008-04-17 15:52:23 +0200 | [diff] [blame] | 950 | if self._uptodate is None: |
| 951 | return True |
| 952 | return self._uptodate() |
| 953 | |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 954 | @property |
| 955 | def debug_info(self): |
| 956 | """The debug info mapping.""" |
| 957 | return [tuple(map(int, x.split('='))) for x in |
| 958 | self._debug_info.split('&')] |
| 959 | |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 960 | def __repr__(self): |
| Armin Ronacher | 5304229 | 2008-04-26 18:30:19 +0200 | [diff] [blame] | 961 | if self.name is None: |
| 962 | name = 'memory:%x' % id(self) |
| 963 | else: |
| 964 | name = repr(self.name) |
| 965 | return '<%s %s>' % (self.__class__.__name__, name) |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 966 | |
| 967 | |
| Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 968 | class TemplateModule(object): |
| 969 | """Represents an imported template. All the exported names of the |
| Armin Ronacher | 5304229 | 2008-04-26 18:30:19 +0200 | [diff] [blame] | 970 | template are available as attributes on this object. Additionally |
| 971 | converting it into an unicode- or bytestrings renders the contents. |
| 972 | """ |
| Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 973 | |
| 974 | def __init__(self, template, context): |
| Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 975 | self._body_stream = list(template.root_render_func(context)) |
| Armin Ronacher | 6ce170c | 2008-04-25 12:32:36 +0200 | [diff] [blame] | 976 | self.__dict__.update(context.get_exported()) |
| Armin Ronacher | 2feed1d | 2008-04-26 16:26:52 +0200 | [diff] [blame] | 977 | self.__name__ = template.name |
| Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 978 | |
| Armin Ronacher | 0faa861 | 2010-02-09 15:04:51 +0100 | [diff] [blame] | 979 | def __html__(self): |
| 980 | return Markup(concat(self._body_stream)) |
| Armin Ronacher | 6ce170c | 2008-04-25 12:32:36 +0200 | [diff] [blame] | 981 | |
| 982 | def __str__(self): |
| Armin Ronacher | 2feed1d | 2008-04-26 16:26:52 +0200 | [diff] [blame] | 983 | return unicode(self).encode('utf-8') |
| Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 984 | |
| Armin Ronacher | acbd408 | 2010-02-10 00:07:43 +0100 | [diff] [blame] | 985 | # unicode goes after __str__ because we configured 2to3 to rename |
| 986 | # __unicode__ to __str__. because the 2to3 tree is not designed to |
| 987 | # remove nodes from it, we leave the above __str__ around and let |
| 988 | # it override at runtime. |
| Armin Ronacher | 790b8a8 | 2010-02-10 00:05:46 +0100 | [diff] [blame] | 989 | def __unicode__(self): |
| 990 | return concat(self._body_stream) |
| 991 | |
| Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 992 | def __repr__(self): |
| Armin Ronacher | 5304229 | 2008-04-26 18:30:19 +0200 | [diff] [blame] | 993 | if self.__name__ is None: |
| 994 | name = 'memory:%x' % id(self) |
| 995 | else: |
| Armin Ronacher | dc02b64 | 2008-05-15 22:47:27 +0200 | [diff] [blame] | 996 | name = repr(self.__name__) |
| Armin Ronacher | 5304229 | 2008-04-26 18:30:19 +0200 | [diff] [blame] | 997 | return '<%s %s>' % (self.__class__.__name__, name) |
| Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 998 | |
| 999 | |
| Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 1000 | class TemplateExpression(object): |
| 1001 | """The :meth:`jinja2.Environment.compile_expression` method returns an |
| 1002 | instance of this object. It encapsulates the expression-like access |
| 1003 | to the template with an expression it wraps. |
| 1004 | """ |
| 1005 | |
| 1006 | def __init__(self, template, undefined_to_none): |
| 1007 | self._template = template |
| 1008 | self._undefined_to_none = undefined_to_none |
| 1009 | |
| 1010 | def __call__(self, *args, **kwargs): |
| 1011 | context = self._template.new_context(dict(*args, **kwargs)) |
| 1012 | consume(self._template.root_render_func(context)) |
| 1013 | rv = context.vars['result'] |
| 1014 | if self._undefined_to_none and isinstance(rv, Undefined): |
| 1015 | rv = None |
| 1016 | return rv |
| 1017 | |
| 1018 | |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1019 | class TemplateStream(object): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 1020 | """A template stream works pretty much like an ordinary python generator |
| 1021 | but it can buffer multiple items to reduce the number of total iterations. |
| 1022 | Per default the output is unbuffered which means that for every unbuffered |
| 1023 | instruction in the template one unicode string is yielded. |
| 1024 | |
| 1025 | If buffering is enabled with a buffer size of 5, five items are combined |
| 1026 | into a new unicode string. This is mainly useful if you are streaming |
| 1027 | big templates to a client via WSGI which flushes after each iteration. |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 1028 | """ |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1029 | |
| 1030 | def __init__(self, gen): |
| 1031 | self._gen = gen |
| Armin Ronacher | 9cf9591 | 2008-05-24 19:54:43 +0200 | [diff] [blame] | 1032 | self.disable_buffering() |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1033 | |
| Armin Ronacher | 74b5106 | 2008-06-17 11:28:59 +0200 | [diff] [blame] | 1034 | def dump(self, fp, encoding=None, errors='strict'): |
| 1035 | """Dump the complete stream into a file or file-like object. |
| 1036 | Per default unicode strings are written, if you want to encode |
| 1037 | before writing specifiy an `encoding`. |
| 1038 | |
| 1039 | Example usage:: |
| 1040 | |
| 1041 | Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') |
| 1042 | """ |
| 1043 | close = False |
| 1044 | if isinstance(fp, basestring): |
| 1045 | fp = file(fp, 'w') |
| 1046 | close = True |
| 1047 | try: |
| 1048 | if encoding is not None: |
| 1049 | iterable = (x.encode(encoding, errors) for x in self) |
| 1050 | else: |
| 1051 | iterable = self |
| 1052 | if hasattr(fp, 'writelines'): |
| 1053 | fp.writelines(iterable) |
| 1054 | else: |
| 1055 | for item in iterable: |
| 1056 | fp.write(item) |
| 1057 | finally: |
| 1058 | if close: |
| 1059 | fp.close() |
| 1060 | |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1061 | def disable_buffering(self): |
| 1062 | """Disable the output buffering.""" |
| 1063 | self._next = self._gen.next |
| 1064 | self.buffered = False |
| 1065 | |
| 1066 | def enable_buffering(self, size=5): |
| Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 1067 | """Enable buffering. Buffer `size` items before yielding them.""" |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1068 | if size <= 1: |
| 1069 | raise ValueError('buffer size too small') |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1070 | |
| Armin Ronacher | 5dfbfc1 | 2008-05-25 18:10:12 +0200 | [diff] [blame] | 1071 | def generator(next): |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1072 | buf = [] |
| 1073 | c_size = 0 |
| 1074 | push = buf.append |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1075 | |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 1076 | while 1: |
| 1077 | try: |
| Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 1078 | while c_size < size: |
| Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 1079 | c = next() |
| 1080 | push(c) |
| 1081 | if c: |
| 1082 | c_size += 1 |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 1083 | except StopIteration: |
| 1084 | if not c_size: |
| Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 1085 | return |
| Armin Ronacher | de6bf71 | 2008-04-26 01:44:14 +0200 | [diff] [blame] | 1086 | yield concat(buf) |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 1087 | del buf[:] |
| 1088 | c_size = 0 |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1089 | |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 1090 | self.buffered = True |
| Armin Ronacher | 5dfbfc1 | 2008-05-25 18:10:12 +0200 | [diff] [blame] | 1091 | self._next = generator(self._gen.next).next |
| Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 1092 | |
| 1093 | def __iter__(self): |
| 1094 | return self |
| 1095 | |
| 1096 | def next(self): |
| 1097 | return self._next() |
| Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 1098 | |
| 1099 | |
| 1100 | # hook in default template class. if anyone reads this comment: ignore that |
| 1101 | # it's possible to use custom templates ;-) |
| 1102 | Environment.template_class = Template |