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 | 62ccd1b | 2009-01-04 14:26:19 +0100 | [diff] [blame] | 8 | :copyright: (c) 2009 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 | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 11 | import sys |
Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 12 | from jinja2 import nodes |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 13 | from jinja2.defaults import * |
Armin Ronacher | 9a0078d | 2008-08-13 18:24:17 +0200 | [diff] [blame] | 14 | from jinja2.lexer import get_lexer, TokenStream |
Armin Ronacher | 0553093 | 2008-04-20 13:27:49 +0200 | [diff] [blame] | 15 | from jinja2.parser import Parser |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 16 | from jinja2.optimizer import optimize |
| 17 | from jinja2.compiler import generate |
Armin Ronacher | 74a0cd9 | 2009-02-19 15:56:53 +0100 | [diff] [blame] | 18 | from jinja2.runtime import Undefined, new_context |
Armin Ronacher | aaf010d | 2008-05-01 13:14:30 +0200 | [diff] [blame] | 19 | from jinja2.exceptions import TemplateSyntaxError |
Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 20 | from jinja2.utils import import_string, LRUCache, Markup, missing, \ |
Armin Ronacher | d416a97 | 2009-02-24 22:58:00 +0100 | [diff] [blame] | 21 | concat, consume, internalcode |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 22 | |
| 23 | |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 24 | # for direct template usage we have up to ten living environments |
| 25 | _spontaneous_environments = LRUCache(10) |
| 26 | |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 27 | # the function to create jinja traceback objects. This is dynamically |
| 28 | # imported on the first exception in the exception handler. |
| 29 | _make_traceback = None |
| 30 | |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 31 | |
Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 32 | def get_spontaneous_environment(*args): |
Georg Brandl | 3e497b7 | 2008-09-19 09:55:17 +0000 | [diff] [blame] | 33 | """Return a new spontaneous environment. A spontaneous environment is an |
| 34 | unnamed and unaccessible (in theory) environment that is used for |
| 35 | templates generated from a string and not from the file system. |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 36 | """ |
| 37 | try: |
| 38 | env = _spontaneous_environments.get(args) |
| 39 | except TypeError: |
| 40 | return Environment(*args) |
| 41 | if env is not None: |
| 42 | return env |
| 43 | _spontaneous_environments[args] = env = Environment(*args) |
Armin Ronacher | c9705c2 | 2008-04-27 21:28:03 +0200 | [diff] [blame] | 44 | env.shared = True |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 45 | return env |
| 46 | |
| 47 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 48 | def create_cache(size): |
| 49 | """Return the cache class for the given size.""" |
| 50 | if size == 0: |
| 51 | return None |
| 52 | if size < 0: |
| 53 | return {} |
| 54 | return LRUCache(size) |
| 55 | |
| 56 | |
Armin Ronacher | ccae055 | 2008-10-05 23:08:58 +0200 | [diff] [blame] | 57 | def copy_cache(cache): |
| 58 | """Create an empty copy of the given cache.""" |
| 59 | if cache is None: |
Armin Ronacher | 2bc1ef7 | 2008-12-08 15:21:26 +0100 | [diff] [blame] | 60 | return None |
Armin Ronacher | ccae055 | 2008-10-05 23:08:58 +0200 | [diff] [blame] | 61 | elif type(cache) is dict: |
| 62 | return {} |
| 63 | return LRUCache(cache.capacity) |
| 64 | |
| 65 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 66 | def load_extensions(environment, extensions): |
| 67 | """Load the extensions from the list and bind it to the environment. |
Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 68 | Returns a dict of instanciated environments. |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 69 | """ |
Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 70 | result = {} |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 71 | for extension in extensions: |
| 72 | if isinstance(extension, basestring): |
| 73 | extension = import_string(extension) |
Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 74 | result[extension.identifier] = extension(environment) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 75 | return result |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 76 | |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 77 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 78 | def _environment_sanity_check(environment): |
| 79 | """Perform a sanity check on the environment.""" |
| 80 | assert issubclass(environment.undefined, Undefined), 'undefined must ' \ |
| 81 | 'be a subclass of undefined because filters depend on it.' |
| 82 | assert environment.block_start_string != \ |
| 83 | environment.variable_start_string != \ |
| 84 | environment.comment_start_string, 'block, variable and comment ' \ |
| 85 | 'start strings must be different' |
Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 86 | assert environment.newline_sequence in ('\r', '\r\n', '\n'), \ |
| 87 | 'newline_sequence set to unknown line ending string.' |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 88 | return environment |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 89 | |
| 90 | |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 91 | class Environment(object): |
Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 92 | r"""The core component of Jinja is the `Environment`. It contains |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 93 | important shared variables like configuration, filters, tests, |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 94 | globals and others. Instances of this class may be modified if |
| 95 | they are not shared and if no template was loaded so far. |
| 96 | Modifications on environments after the first template was loaded |
| 97 | will lead to surprising effects and undefined behavior. |
| 98 | |
| 99 | Here the possible initialization parameters: |
| 100 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 101 | `block_start_string` |
| 102 | The string marking the begin of a block. Defaults to ``'{%'``. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 103 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 104 | `block_end_string` |
| 105 | The string marking the end of a block. Defaults to ``'%}'``. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 106 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 107 | `variable_start_string` |
| 108 | The string marking the begin of a print statement. |
| 109 | Defaults to ``'{{'``. |
Armin Ronacher | 115de2e | 2008-05-01 22:20:05 +0200 | [diff] [blame] | 110 | |
Armin Ronacher | 63fd798 | 2008-06-20 18:47:56 +0200 | [diff] [blame] | 111 | `variable_end_string` |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 112 | The string marking the end of a print statement. Defaults to |
| 113 | ``'}}'``. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 114 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 115 | `comment_start_string` |
| 116 | The string marking the begin of a comment. Defaults to ``'{#'``. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 117 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 118 | `comment_end_string` |
| 119 | The string marking the end of a comment. Defaults to ``'#}'``. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 120 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 121 | `line_statement_prefix` |
| 122 | If given and a string, this will be used as prefix for line based |
| 123 | statements. See also :ref:`line-statements`. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 124 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 125 | `trim_blocks` |
| 126 | If this is set to ``True`` the first newline after a block is |
| 127 | removed (block, not variable tag!). Defaults to `False`. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 128 | |
Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 129 | `newline_sequence` |
| 130 | The sequence that starts a newline. Must be one of ``'\r'``, |
| 131 | ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a |
| 132 | useful default for Linux and OS X systems as well as web |
| 133 | applications. |
| 134 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 135 | `extensions` |
| 136 | List of Jinja extensions to use. This can either be import paths |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 137 | as strings or extension classes. For more information have a |
| 138 | look at :ref:`the extensions documentation <jinja-extensions>`. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 139 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 140 | `optimized` |
| 141 | should the optimizer be enabled? Default is `True`. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 142 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 143 | `undefined` |
| 144 | :class:`Undefined` or a subclass of it that is used to represent |
| 145 | undefined values in the template. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 146 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 147 | `finalize` |
| 148 | A callable that finalizes the variable. Per default no finalizing |
| 149 | is applied. |
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 | `autoescape` |
| 152 | If set to true the XML/HTML autoescaping feature is enabled. |
Armin Ronacher | f7e405d | 2008-09-08 23:57:26 +0200 | [diff] [blame] | 153 | For more details about auto escaping see |
| 154 | :class:`~jinja2.utils.Markup`. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 155 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 156 | `loader` |
| 157 | The template loader for this environment. |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 158 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 159 | `cache_size` |
| 160 | The size of the cache. Per default this is ``50`` which means |
| 161 | that if more than 50 templates are loaded the loader will clean |
| 162 | out the least recently used template. If the cache size is set to |
| 163 | ``0`` templates are recompiled all the time, if the cache size is |
| 164 | ``-1`` the cache will not be cleaned. |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 165 | |
Armin Ronacher | 7b5680c | 2008-05-06 16:54:22 +0200 | [diff] [blame] | 166 | `auto_reload` |
| 167 | Some loaders load templates from locations where the template |
| 168 | sources may change (ie: file system or database). If |
| 169 | `auto_reload` is set to `True` (default) every time a template is |
| 170 | requested the loader checks if the source changed and if yes, it |
| 171 | will reload the template. For higher performance it's possible to |
| 172 | disable that. |
Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 173 | |
| 174 | `bytecode_cache` |
| 175 | If set to a bytecode cache object, this object will provide a |
| 176 | cache for the internal Jinja bytecode so that templates don't |
| 177 | have to be parsed if they were not changed. |
Armin Ronacher | a816bf4 | 2008-09-17 21:28:01 +0200 | [diff] [blame] | 178 | |
| 179 | See :ref:`bytecode-cache` for more information. |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 180 | """ |
| 181 | |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 182 | #: if this environment is sandboxed. Modifying this variable won't make |
| 183 | #: the environment sandboxed though. For a real sandboxed environment |
| 184 | #: have a look at jinja2.sandbox |
| 185 | sandboxed = False |
| 186 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 187 | #: True if the environment is just an overlay |
| 188 | overlay = False |
| 189 | |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 190 | #: the environment this environment is linked to if it is an overlay |
| 191 | linked_to = None |
| 192 | |
Armin Ronacher | c9705c2 | 2008-04-27 21:28:03 +0200 | [diff] [blame] | 193 | #: shared environments have this set to `True`. A shared environment |
| 194 | #: must not be modified |
| 195 | shared = False |
| 196 | |
Armin Ronacher | 32ed6c9 | 2009-04-02 14:04:41 +0200 | [diff] [blame^] | 197 | #: these are currently EXPERIMENTAL undocumented features. |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 198 | exception_handler = None |
| 199 | exception_formatter = None |
| 200 | |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 201 | def __init__(self, |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 202 | block_start_string=BLOCK_START_STRING, |
| 203 | block_end_string=BLOCK_END_STRING, |
| 204 | variable_start_string=VARIABLE_START_STRING, |
| 205 | variable_end_string=VARIABLE_END_STRING, |
| 206 | comment_start_string=COMMENT_START_STRING, |
| 207 | comment_end_string=COMMENT_END_STRING, |
| 208 | line_statement_prefix=LINE_STATEMENT_PREFIX, |
Armin Ronacher | 4f5008f | 2008-05-23 23:36:07 +0200 | [diff] [blame] | 209 | trim_blocks=TRIM_BLOCKS, |
| 210 | newline_sequence=NEWLINE_SEQUENCE, |
Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 211 | extensions=(), |
Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 212 | optimized=True, |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 213 | undefined=Undefined, |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 214 | finalize=None, |
| 215 | autoescape=False, |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 216 | loader=None, |
| 217 | cache_size=50, |
Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 218 | auto_reload=True, |
| 219 | bytecode_cache=None): |
Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 220 | # !!Important notice!! |
| 221 | # The constructor accepts quite a few arguments that should be |
| 222 | # passed by keyword rather than position. However it's important to |
| 223 | # not change the order of arguments because it's used at least |
| 224 | # internally in those cases: |
| 225 | # - spontaneus environments (i18n extension and Template) |
| 226 | # - unittests |
| 227 | # If parameter changes are required only add parameters at the end |
| 228 | # and don't change the arguments (or the defaults!) of the arguments |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 229 | # existing already. |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 230 | |
| 231 | # lexer / parser information |
| 232 | self.block_start_string = block_start_string |
| 233 | self.block_end_string = block_end_string |
| 234 | self.variable_start_string = variable_start_string |
| 235 | self.variable_end_string = variable_end_string |
| 236 | self.comment_start_string = comment_start_string |
| 237 | self.comment_end_string = comment_end_string |
Armin Ronacher | bf7c4ad | 2008-04-12 12:02:36 +0200 | [diff] [blame] | 238 | self.line_statement_prefix = line_statement_prefix |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 239 | self.trim_blocks = trim_blocks |
Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 240 | self.newline_sequence = newline_sequence |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 241 | |
Armin Ronacher | f59bac2 | 2008-04-20 13:11:43 +0200 | [diff] [blame] | 242 | # runtime information |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 243 | self.undefined = undefined |
Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 244 | self.optimized = optimized |
Armin Ronacher | 18c6ca0 | 2008-04-17 10:03:29 +0200 | [diff] [blame] | 245 | self.finalize = finalize |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 246 | self.autoescape = autoescape |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 247 | |
| 248 | # defaults |
| 249 | self.filters = DEFAULT_FILTERS.copy() |
| 250 | self.tests = DEFAULT_TESTS.copy() |
| 251 | self.globals = DEFAULT_NAMESPACE.copy() |
| 252 | |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 253 | # set the loader provided |
| 254 | self.loader = loader |
Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 255 | self.bytecode_cache = None |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 256 | self.cache = create_cache(cache_size) |
Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 257 | self.bytecode_cache = bytecode_cache |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 258 | self.auto_reload = auto_reload |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 259 | |
Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 260 | # load extensions |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 261 | self.extensions = load_extensions(self, extensions) |
| 262 | |
| 263 | _environment_sanity_check(self) |
| 264 | |
Armin Ronacher | 762079c | 2008-05-08 23:57:56 +0200 | [diff] [blame] | 265 | def extend(self, **attributes): |
| 266 | """Add the items to the instance of the environment if they do not exist |
| 267 | yet. This is used by :ref:`extensions <writing-extensions>` to register |
| 268 | callbacks and configuration values without breaking inheritance. |
| 269 | """ |
| 270 | for key, value in attributes.iteritems(): |
| 271 | if not hasattr(self, key): |
| 272 | setattr(self, key, value) |
| 273 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 274 | def overlay(self, block_start_string=missing, block_end_string=missing, |
| 275 | variable_start_string=missing, variable_end_string=missing, |
| 276 | comment_start_string=missing, comment_end_string=missing, |
| 277 | line_statement_prefix=missing, trim_blocks=missing, |
| 278 | extensions=missing, optimized=missing, undefined=missing, |
| 279 | finalize=missing, autoescape=missing, loader=missing, |
Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 280 | cache_size=missing, auto_reload=missing, |
| 281 | bytecode_cache=missing): |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 282 | """Create a new overlay environment that shares all the data with the |
| 283 | current environment except of cache and the overriden attributes. |
| 284 | Extensions cannot be removed for a overlayed environment. A overlayed |
| 285 | environment automatically gets all the extensions of the environment it |
| 286 | is linked to plus optional extra extensions. |
| 287 | |
| 288 | Creating overlays should happen after the initial environment was set |
| 289 | up completely. Not all attributes are truly linked, some are just |
| 290 | copied over so modifications on the original environment may not shine |
| 291 | through. |
| 292 | """ |
| 293 | args = dict(locals()) |
| 294 | del args['self'], args['cache_size'], args['extensions'] |
| 295 | |
| 296 | rv = object.__new__(self.__class__) |
| 297 | rv.__dict__.update(self.__dict__) |
| 298 | rv.overlay = True |
| 299 | rv.linked_to = self |
| 300 | |
| 301 | for key, value in args.iteritems(): |
| 302 | if value is not missing: |
| 303 | setattr(rv, key, value) |
| 304 | |
| 305 | if cache_size is not missing: |
| 306 | rv.cache = create_cache(cache_size) |
Armin Ronacher | ccae055 | 2008-10-05 23:08:58 +0200 | [diff] [blame] | 307 | else: |
| 308 | rv.cache = copy_cache(self.cache) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 309 | |
Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 310 | rv.extensions = {} |
| 311 | for key, value in self.extensions.iteritems(): |
| 312 | rv.extensions[key] = value.bind(rv) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 313 | if extensions is not missing: |
Armin Ronacher | 023b5e9 | 2008-05-08 11:03:10 +0200 | [diff] [blame] | 314 | rv.extensions.update(load_extensions(extensions)) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 315 | |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 316 | return _environment_sanity_check(rv) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 317 | |
Armin Ronacher | 9a0078d | 2008-08-13 18:24:17 +0200 | [diff] [blame] | 318 | lexer = property(get_lexer, doc="The lexer for this environment.") |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 319 | |
Armin Ronacher | 6dc6f29 | 2008-06-12 08:50:07 +0200 | [diff] [blame] | 320 | def getitem(self, obj, argument): |
| 321 | """Get an item or attribute of an object but prefer the item.""" |
Armin Ronacher | 08a6a3b | 2008-05-13 15:35:47 +0200 | [diff] [blame] | 322 | try: |
| 323 | return obj[argument] |
| 324 | except (TypeError, LookupError): |
Armin Ronacher | f15f5f7 | 2008-05-26 12:21:45 +0200 | [diff] [blame] | 325 | if isinstance(argument, basestring): |
| 326 | try: |
| 327 | attr = str(argument) |
| 328 | except: |
| 329 | pass |
| 330 | else: |
| 331 | try: |
| 332 | return getattr(obj, attr) |
| 333 | except AttributeError: |
| 334 | pass |
Armin Ronacher | 08a6a3b | 2008-05-13 15:35:47 +0200 | [diff] [blame] | 335 | return self.undefined(obj=obj, name=argument) |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 336 | |
Armin Ronacher | 6dc6f29 | 2008-06-12 08:50:07 +0200 | [diff] [blame] | 337 | def getattr(self, obj, attribute): |
| 338 | """Get an item or attribute of an object but prefer the attribute. |
| 339 | Unlike :meth:`getitem` the attribute *must* be a bytestring. |
| 340 | """ |
| 341 | try: |
| 342 | return getattr(obj, attribute) |
| 343 | except AttributeError: |
| 344 | pass |
| 345 | try: |
| 346 | return obj[attribute] |
Christopher Grebs | f1c940f | 2008-07-10 11:52:17 +0200 | [diff] [blame] | 347 | except (TypeError, LookupError, AttributeError): |
Armin Ronacher | 6dc6f29 | 2008-06-12 08:50:07 +0200 | [diff] [blame] | 348 | return self.undefined(obj=obj, name=attribute) |
| 349 | |
Armin Ronacher | d416a97 | 2009-02-24 22:58:00 +0100 | [diff] [blame] | 350 | @internalcode |
Armin Ronacher | 7f15ef8 | 2008-05-16 09:11:39 +0200 | [diff] [blame] | 351 | def parse(self, source, name=None, filename=None): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 352 | """Parse the sourcecode and return the abstract syntax tree. This |
| 353 | tree of nodes is used by the compiler to convert the template into |
| 354 | executable source- or bytecode. This is useful for debugging or to |
| 355 | extract information from templates. |
Armin Ronacher | ed98cac | 2008-05-07 08:42:11 +0200 | [diff] [blame] | 356 | |
| 357 | If you are :ref:`developing Jinja2 extensions <writing-extensions>` |
| 358 | this gives you a good overview of the node tree generated. |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 359 | """ |
Armin Ronacher | 67fdddf | 2008-05-16 09:27:51 +0200 | [diff] [blame] | 360 | if isinstance(filename, unicode): |
| 361 | filename = filename.encode('utf-8') |
Armin Ronacher | aaf010d | 2008-05-01 13:14:30 +0200 | [diff] [blame] | 362 | try: |
Armin Ronacher | 7f15ef8 | 2008-05-16 09:11:39 +0200 | [diff] [blame] | 363 | return Parser(self, source, name, filename).parse() |
Armin Ronacher | aaf010d | 2008-05-01 13:14:30 +0200 | [diff] [blame] | 364 | except TemplateSyntaxError, e: |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 365 | self.handle_exception(sys.exc_info(), source_hint=source) |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 366 | |
Armin Ronacher | 7f15ef8 | 2008-05-16 09:11:39 +0200 | [diff] [blame] | 367 | def lex(self, source, name=None, filename=None): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 368 | """Lex the given sourcecode and return a generator that yields |
| 369 | tokens as tuples in the form ``(lineno, token_type, value)``. |
Armin Ronacher | 5cdc1ac | 2008-05-07 12:17:18 +0200 | [diff] [blame] | 370 | This can be useful for :ref:`extension development <writing-extensions>` |
| 371 | and debugging templates. |
Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 372 | |
| 373 | This does not perform preprocessing. If you want the preprocessing |
| 374 | of the extensions to be applied you have to filter source through |
| 375 | the :meth:`preprocess` method. |
Armin Ronacher | 07bc684 | 2008-03-31 14:18:49 +0200 | [diff] [blame] | 376 | """ |
Armin Ronacher | ccae055 | 2008-10-05 23:08:58 +0200 | [diff] [blame] | 377 | source = unicode(source) |
| 378 | try: |
| 379 | return self.lexer.tokeniter(source, name, filename) |
| 380 | except TemplateSyntaxError, e: |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 381 | self.handle_exception(sys.exc_info(), source_hint=source) |
Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 382 | |
| 383 | def preprocess(self, source, name=None, filename=None): |
| 384 | """Preprocesses the source with all extensions. This is automatically |
| 385 | called for all parsing and compiling methods but *not* for :meth:`lex` |
| 386 | because there you usually only want the actual source tokenized. |
| 387 | """ |
| 388 | return reduce(lambda s, e: e.preprocess(s, name, filename), |
| 389 | self.extensions.itervalues(), unicode(source)) |
| 390 | |
Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 391 | def _tokenize(self, source, name, filename=None, state=None): |
Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 392 | """Called by the parser to do the preprocessing and filtering |
| 393 | for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`. |
| 394 | """ |
Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 395 | source = self.preprocess(source, name, filename) |
Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 396 | stream = self.lexer.tokenize(source, name, filename, state) |
Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 397 | for ext in self.extensions.itervalues(): |
Armin Ronacher | 3e3a9be | 2008-06-14 12:44:15 +0200 | [diff] [blame] | 398 | stream = ext.filter_stream(stream) |
| 399 | if not isinstance(stream, TokenStream): |
| 400 | stream = TokenStream(stream, name, filename) |
Armin Ronacher | 9ad96e7 | 2008-06-13 22:44:01 +0200 | [diff] [blame] | 401 | return stream |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 402 | |
Armin Ronacher | d416a97 | 2009-02-24 22:58:00 +0100 | [diff] [blame] | 403 | @internalcode |
Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 404 | def compile(self, source, name=None, filename=None, raw=False): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 405 | """Compile a node or template source code. The `name` parameter is |
| 406 | the load name of the template after it was joined using |
| 407 | :meth:`join_path` if necessary, not the filename on the file system. |
| 408 | the `filename` parameter is the estimated filename of the template on |
| 409 | 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] | 410 | can be omitted. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 411 | |
| 412 | The return value of this method is a python code object. If the `raw` |
| 413 | parameter is `True` the return value will be a string with python |
| 414 | code equivalent to the bytecode returned otherwise. This method is |
| 415 | mainly used internally. |
Armin Ronacher | 68f7767 | 2008-04-17 11:50:39 +0200 | [diff] [blame] | 416 | """ |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 417 | if isinstance(source, basestring): |
Armin Ronacher | 7f15ef8 | 2008-05-16 09:11:39 +0200 | [diff] [blame] | 418 | source = self.parse(source, name, filename) |
Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 419 | if self.optimized: |
Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 420 | source = optimize(source, self) |
| 421 | source = generate(source, self, name, filename) |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 422 | if raw: |
| 423 | return source |
Armin Ronacher | 2e9396b | 2008-04-16 14:21:57 +0200 | [diff] [blame] | 424 | if filename is None: |
Armin Ronacher | 68f7767 | 2008-04-17 11:50:39 +0200 | [diff] [blame] | 425 | filename = '<template>' |
Armin Ronacher | 2e9396b | 2008-04-16 14:21:57 +0200 | [diff] [blame] | 426 | elif isinstance(filename, unicode): |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 427 | filename = filename.encode('utf-8') |
| 428 | return compile(source, filename, 'exec') |
| 429 | |
Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 430 | def compile_expression(self, source, undefined_to_none=True): |
| 431 | """A handy helper method that returns a callable that accepts keyword |
| 432 | arguments that appear as variables in the expression. If called it |
| 433 | returns the result of the expression. |
| 434 | |
| 435 | This is useful if applications want to use the same rules as Jinja |
| 436 | in template "configuration files" or similar situations. |
| 437 | |
| 438 | Example usage: |
| 439 | |
| 440 | >>> env = Environment() |
| 441 | >>> expr = env.compile_expression('foo == 42') |
| 442 | >>> expr(foo=23) |
| 443 | False |
| 444 | >>> expr(foo=42) |
| 445 | True |
| 446 | |
| 447 | Per default the return value is converted to `None` if the |
| 448 | expression returns an undefined value. This can be changed |
| 449 | by setting `undefined_to_none` to `False`. |
| 450 | |
| 451 | >>> env.compile_expression('var')() is None |
| 452 | True |
| 453 | >>> env.compile_expression('var', undefined_to_none=False)() |
| 454 | Undefined |
| 455 | |
| 456 | **new in Jinja 2.1** |
| 457 | """ |
| 458 | parser = Parser(self, source, state='variable') |
| 459 | try: |
| 460 | expr = parser.parse_expression() |
| 461 | if not parser.stream.eos: |
| 462 | raise TemplateSyntaxError('chunk after expression', |
| 463 | parser.stream.current.lineno, |
| 464 | None, None) |
| 465 | except TemplateSyntaxError, e: |
| 466 | e.source = source |
| 467 | raise e |
| 468 | body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)] |
| 469 | template = self.from_string(nodes.Template(body, lineno=1)) |
| 470 | return TemplateExpression(template, undefined_to_none) |
| 471 | |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 472 | def handle_exception(self, exc_info=None, rendered=False, source_hint=None): |
| 473 | """Exception handling helper. This is used internally to either raise |
| 474 | rewritten exceptions or return a rendered traceback for the template. |
| 475 | """ |
| 476 | global _make_traceback |
| 477 | if exc_info is None: |
| 478 | exc_info = sys.exc_info() |
Armin Ronacher | 32ed6c9 | 2009-04-02 14:04:41 +0200 | [diff] [blame^] | 479 | |
| 480 | # the debugging module is imported when it's used for the first time. |
| 481 | # we're doing a lot of stuff there and for applications that do not |
| 482 | # get any exceptions in template rendering there is no need to load |
| 483 | # all of that. |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 484 | if _make_traceback is None: |
| 485 | from jinja2.debug import make_traceback as _make_traceback |
Armin Ronacher | 32ed6c9 | 2009-04-02 14:04:41 +0200 | [diff] [blame^] | 486 | |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 487 | traceback = _make_traceback(exc_info, source_hint) |
Armin Ronacher | 32ed6c9 | 2009-04-02 14:04:41 +0200 | [diff] [blame^] | 488 | |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 489 | if rendered and self.exception_formatter is not None: |
| 490 | return self.exception_formatter(traceback) |
| 491 | if self.exception_handler is not None: |
| 492 | self.exception_handler(traceback) |
Armin Ronacher | 32ed6c9 | 2009-04-02 14:04:41 +0200 | [diff] [blame^] | 493 | |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 494 | exc_type, exc_value, tb = traceback.standard_exc_info |
| 495 | raise exc_type, exc_value, tb |
| 496 | |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 497 | def join_path(self, template, parent): |
| 498 | """Join a template with the parent. By default all the lookups are |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 499 | relative to the loader root so this method returns the `template` |
| 500 | parameter unchanged, but if the paths should be relative to the |
| 501 | parent template, this function can be used to calculate the real |
| 502 | template name. |
| 503 | |
| 504 | Subclasses may override this method and implement template path |
| 505 | joining here. |
| 506 | """ |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 507 | return template |
| 508 | |
Armin Ronacher | d416a97 | 2009-02-24 22:58:00 +0100 | [diff] [blame] | 509 | @internalcode |
Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 510 | def get_template(self, name, parent=None, globals=None): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 511 | """Load a template from the loader. If a loader is configured this |
| 512 | method ask the loader for the template and returns a :class:`Template`. |
| 513 | If the `parent` parameter is not `None`, :meth:`join_path` is called |
| 514 | to get the real template name before loading. |
| 515 | |
Armin Ronacher | 7a519ee | 2008-09-08 23:10:47 +0200 | [diff] [blame] | 516 | The `globals` parameter can be used to provide template wide globals. |
Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 517 | These variables are available in the context at render time. |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 518 | |
| 519 | If the template does not exist a :exc:`TemplateNotFound` exception is |
| 520 | raised. |
| 521 | """ |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 522 | if self.loader is None: |
| 523 | raise TypeError('no loader for this environment specified') |
| 524 | if parent is not None: |
| 525 | name = self.join_path(name, parent) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 526 | |
| 527 | if self.cache is not None: |
| 528 | template = self.cache.get(name) |
| 529 | if template is not None and (not self.auto_reload or \ |
| 530 | template.is_up_to_date): |
| 531 | return template |
| 532 | |
| 533 | template = self.loader.load(self, name, self.make_globals(globals)) |
| 534 | if self.cache is not None: |
| 535 | self.cache[name] = template |
| 536 | return template |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 537 | |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 538 | def from_string(self, source, globals=None, template_class=None): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 539 | """Load a template from a string. This parses the source given and |
| 540 | returns a :class:`Template` object. |
| 541 | """ |
Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 542 | globals = self.make_globals(globals) |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 543 | cls = template_class or self.template_class |
Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 544 | return cls.from_code(self, self.compile(source), globals, None) |
Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 545 | |
| 546 | def make_globals(self, d): |
| 547 | """Return a dict for the globals.""" |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 548 | if not d: |
Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 549 | return self.globals |
| 550 | return dict(self.globals, **d) |
Armin Ronacher | 46f5f98 | 2008-04-11 16:40:09 +0200 | [diff] [blame] | 551 | |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 552 | |
| 553 | class Template(object): |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 554 | """The central template object. This class represents a compiled template |
| 555 | and is used to evaluate it. |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 556 | |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 557 | Normally the template object is generated from an :class:`Environment` but |
| 558 | 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] | 559 | instance directly using the constructor. It takes the same arguments as |
| 560 | the environment constructor but it's not possible to specify a loader. |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 561 | |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 562 | Every template object has a few methods and members that are guaranteed |
| 563 | to exist. However it's important that a template object should be |
| 564 | considered immutable. Modifications on the object are not supported. |
| 565 | |
| 566 | Template objects created from the constructor rather than an environment |
| 567 | do have an `environment` attribute that points to a temporary environment |
| 568 | that is probably shared with other templates created with the constructor |
| 569 | and compatible settings. |
| 570 | |
| 571 | >>> template = Template('Hello {{ name }}!') |
| 572 | >>> template.render(name='John Doe') |
| 573 | u'Hello John Doe!' |
| 574 | |
| 575 | >>> stream = template.stream(name='John Doe') |
| 576 | >>> stream.next() |
| 577 | u'Hello John Doe!' |
| 578 | >>> stream.next() |
| 579 | Traceback (most recent call last): |
| 580 | ... |
| 581 | StopIteration |
| 582 | """ |
| 583 | |
| 584 | def __new__(cls, source, |
Armin Ronacher | 4f5008f | 2008-05-23 23:36:07 +0200 | [diff] [blame] | 585 | block_start_string=BLOCK_START_STRING, |
| 586 | block_end_string=BLOCK_END_STRING, |
| 587 | variable_start_string=VARIABLE_START_STRING, |
| 588 | variable_end_string=VARIABLE_END_STRING, |
| 589 | comment_start_string=COMMENT_START_STRING, |
| 590 | comment_end_string=COMMENT_END_STRING, |
| 591 | line_statement_prefix=LINE_STATEMENT_PREFIX, |
| 592 | trim_blocks=TRIM_BLOCKS, |
| 593 | newline_sequence=NEWLINE_SEQUENCE, |
Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 594 | extensions=(), |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 595 | optimized=True, |
| 596 | undefined=Undefined, |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 597 | finalize=None, |
| 598 | autoescape=False): |
Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 599 | env = get_spontaneous_environment( |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 600 | block_start_string, block_end_string, variable_start_string, |
| 601 | variable_end_string, comment_start_string, comment_end_string, |
Armin Ronacher | f3c35c4 | 2008-05-23 23:18:14 +0200 | [diff] [blame] | 602 | line_statement_prefix, trim_blocks, newline_sequence, |
| 603 | frozenset(extensions), optimized, undefined, finalize, |
Armin Ronacher | 4d5bdff | 2008-09-17 16:19:46 +0200 | [diff] [blame] | 604 | autoescape, None, 0, False, None) |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 605 | return env.from_string(source, template_class=cls) |
Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 606 | |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 607 | @classmethod |
| 608 | def from_code(cls, environment, code, globals, uptodate=None): |
| 609 | """Creates a template object from compiled code and the globals. This |
| 610 | is used by the loaders and environment to create a template object. |
| 611 | """ |
| 612 | t = object.__new__(cls) |
| 613 | namespace = { |
| 614 | 'environment': environment, |
| 615 | '__jinja_template__': t |
| 616 | } |
| 617 | exec code in namespace |
| 618 | t.environment = environment |
Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 619 | t.globals = globals |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 620 | t.name = namespace['name'] |
| 621 | t.filename = code.co_filename |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 622 | t.blocks = namespace['blocks'] |
Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 623 | |
Georg Brandl | 3e497b7 | 2008-09-19 09:55:17 +0000 | [diff] [blame] | 624 | # render function and module |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 625 | t.root_render_func = namespace['root'] |
Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 626 | t._module = None |
Armin Ronacher | 7259c76 | 2008-04-30 13:03:59 +0200 | [diff] [blame] | 627 | |
| 628 | # debug and loader helpers |
| 629 | t._debug_info = namespace['debug_info'] |
| 630 | t._uptodate = uptodate |
| 631 | |
| 632 | return t |
| 633 | |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 634 | def render(self, *args, **kwargs): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 635 | """This method accepts the same arguments as the `dict` constructor: |
| 636 | A dict, a dict subclass or some keyword arguments. If no arguments |
| 637 | are given the context will be empty. These two calls do the same:: |
| 638 | |
| 639 | template.render(knights='that say nih') |
| 640 | template.render({'knights': 'that say nih'}) |
| 641 | |
| 642 | This will return the rendered template as unicode string. |
| 643 | """ |
Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 644 | vars = dict(*args, **kwargs) |
Armin Ronacher | f41d139 | 2008-04-18 16:41:52 +0200 | [diff] [blame] | 645 | try: |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 646 | return concat(self.root_render_func(self.new_context(vars))) |
Armin Ronacher | f41d139 | 2008-04-18 16:41:52 +0200 | [diff] [blame] | 647 | except: |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 648 | return self.environment.handle_exception(sys.exc_info(), True) |
Armin Ronacher | bcb7c53 | 2008-04-11 16:30:34 +0200 | [diff] [blame] | 649 | |
| 650 | def stream(self, *args, **kwargs): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 651 | """Works exactly like :meth:`generate` but returns a |
| 652 | :class:`TemplateStream`. |
| 653 | """ |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 654 | return TemplateStream(self.generate(*args, **kwargs)) |
Armin Ronacher | fed44b5 | 2008-04-13 19:42:53 +0200 | [diff] [blame] | 655 | |
| 656 | def generate(self, *args, **kwargs): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 657 | """For very large templates it can be useful to not render the whole |
| 658 | template at once but evaluate each statement after another and yield |
| 659 | piece for piece. This method basically does exactly that and returns |
| 660 | a generator that yields one item after another as unicode strings. |
| 661 | |
| 662 | It accepts the same arguments as :meth:`render`. |
| 663 | """ |
Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 664 | vars = dict(*args, **kwargs) |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 665 | try: |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 666 | for event in self.root_render_func(self.new_context(vars)): |
Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 667 | yield event |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 668 | except: |
Armin Ronacher | e73e097 | 2009-03-05 23:47:00 +0100 | [diff] [blame] | 669 | yield self.environment.handle_exception(sys.exc_info(), True) |
Armin Ronacher | 19cf9c2 | 2008-05-01 12:49:53 +0200 | [diff] [blame] | 670 | |
Armin Ronacher | 673aa88 | 2008-10-04 18:06:57 +0200 | [diff] [blame] | 671 | def new_context(self, vars=None, shared=False, locals=None): |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 672 | """Create a new :class:`Context` for this template. The vars |
Armin Ronacher | c9705c2 | 2008-04-27 21:28:03 +0200 | [diff] [blame] | 673 | provided will be passed to the template. Per default the globals |
Armin Ronacher | 673aa88 | 2008-10-04 18:06:57 +0200 | [diff] [blame] | 674 | are added to the context. If shared is set to `True` the data |
| 675 | is passed as it to the context without adding the globals. |
| 676 | |
| 677 | `locals` can be a dict of local variables for internal usage. |
Armin Ronacher | c9705c2 | 2008-04-27 21:28:03 +0200 | [diff] [blame] | 678 | """ |
Armin Ronacher | 74a0cd9 | 2009-02-19 15:56:53 +0100 | [diff] [blame] | 679 | return new_context(self.environment, self.name, self.blocks, |
| 680 | vars, shared, self.globals, locals) |
Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 681 | |
Armin Ronacher | 673aa88 | 2008-10-04 18:06:57 +0200 | [diff] [blame] | 682 | def make_module(self, vars=None, shared=False, locals=None): |
Armin Ronacher | 7ceced5 | 2008-05-03 10:15:31 +0200 | [diff] [blame] | 683 | """This method works like the :attr:`module` attribute when called |
| 684 | without arguments but it will evaluate the template every call |
| 685 | rather then caching the template. It's also possible to provide |
| 686 | 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] | 687 | as for the :meth:`new_context` method. |
Armin Ronacher | ea847c5 | 2008-05-02 20:04:32 +0200 | [diff] [blame] | 688 | """ |
Armin Ronacher | 673aa88 | 2008-10-04 18:06:57 +0200 | [diff] [blame] | 689 | return TemplateModule(self, self.new_context(vars, shared, locals)) |
Armin Ronacher | ea847c5 | 2008-05-02 20:04:32 +0200 | [diff] [blame] | 690 | |
Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 691 | @property |
| 692 | def module(self): |
| 693 | """The template as module. This is used for imports in the |
| 694 | template runtime but is also useful if one wants to access |
| 695 | exported template variables from the Python layer: |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 696 | |
Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 697 | >>> t = Template('{% macro foo() %}42{% endmacro %}23') |
| 698 | >>> unicode(t.module) |
| 699 | u'23' |
| 700 | >>> t.module.foo() |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 701 | u'42' |
Armin Ronacher | 6ce170c | 2008-04-25 12:32:36 +0200 | [diff] [blame] | 702 | """ |
Armin Ronacher | 771c750 | 2008-05-18 23:14:14 +0200 | [diff] [blame] | 703 | if self._module is not None: |
Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 704 | return self._module |
Armin Ronacher | ea847c5 | 2008-05-02 20:04:32 +0200 | [diff] [blame] | 705 | self._module = rv = self.make_module() |
Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 706 | return rv |
Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 707 | |
Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 708 | def get_corresponding_lineno(self, lineno): |
| 709 | """Return the source line number of a line number in the |
| 710 | generated bytecode as they are not in sync. |
| 711 | """ |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 712 | for template_line, code_line in reversed(self.debug_info): |
Armin Ronacher | ba3757b | 2008-04-16 19:43:16 +0200 | [diff] [blame] | 713 | if code_line <= lineno: |
| 714 | return template_line |
| 715 | return 1 |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 716 | |
Armin Ronacher | 9a82205 | 2008-04-17 18:44:07 +0200 | [diff] [blame] | 717 | @property |
Armin Ronacher | 814f6c2 | 2008-04-17 15:52:23 +0200 | [diff] [blame] | 718 | def is_up_to_date(self): |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 719 | """If this variable is `False` there is a newer version available.""" |
Armin Ronacher | 814f6c2 | 2008-04-17 15:52:23 +0200 | [diff] [blame] | 720 | if self._uptodate is None: |
| 721 | return True |
| 722 | return self._uptodate() |
| 723 | |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 724 | @property |
| 725 | def debug_info(self): |
| 726 | """The debug info mapping.""" |
| 727 | return [tuple(map(int, x.split('='))) for x in |
| 728 | self._debug_info.split('&')] |
| 729 | |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 730 | def __repr__(self): |
Armin Ronacher | 5304229 | 2008-04-26 18:30:19 +0200 | [diff] [blame] | 731 | if self.name is None: |
| 732 | name = 'memory:%x' % id(self) |
| 733 | else: |
| 734 | name = repr(self.name) |
| 735 | return '<%s %s>' % (self.__class__.__name__, name) |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 736 | |
| 737 | |
Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 738 | class TemplateModule(object): |
| 739 | """Represents an imported template. All the exported names of the |
Armin Ronacher | 5304229 | 2008-04-26 18:30:19 +0200 | [diff] [blame] | 740 | template are available as attributes on this object. Additionally |
| 741 | converting it into an unicode- or bytestrings renders the contents. |
| 742 | """ |
Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 743 | |
| 744 | def __init__(self, template, context): |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 745 | self._body_stream = list(template.root_render_func(context)) |
Armin Ronacher | 6ce170c | 2008-04-25 12:32:36 +0200 | [diff] [blame] | 746 | self.__dict__.update(context.get_exported()) |
Armin Ronacher | 2feed1d | 2008-04-26 16:26:52 +0200 | [diff] [blame] | 747 | self.__name__ = template.name |
Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 748 | |
Armin Ronacher | bbbe062 | 2008-05-19 00:23:37 +0200 | [diff] [blame] | 749 | __unicode__ = lambda x: concat(x._body_stream) |
Armin Ronacher | 5411ce7 | 2008-05-25 11:36:22 +0200 | [diff] [blame] | 750 | __html__ = lambda x: Markup(concat(x._body_stream)) |
Armin Ronacher | 6ce170c | 2008-04-25 12:32:36 +0200 | [diff] [blame] | 751 | |
| 752 | def __str__(self): |
Armin Ronacher | 2feed1d | 2008-04-26 16:26:52 +0200 | [diff] [blame] | 753 | return unicode(self).encode('utf-8') |
Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 754 | |
| 755 | def __repr__(self): |
Armin Ronacher | 5304229 | 2008-04-26 18:30:19 +0200 | [diff] [blame] | 756 | if self.__name__ is None: |
| 757 | name = 'memory:%x' % id(self) |
| 758 | else: |
Armin Ronacher | dc02b64 | 2008-05-15 22:47:27 +0200 | [diff] [blame] | 759 | name = repr(self.__name__) |
Armin Ronacher | 5304229 | 2008-04-26 18:30:19 +0200 | [diff] [blame] | 760 | return '<%s %s>' % (self.__class__.__name__, name) |
Armin Ronacher | 963f97d | 2008-04-25 11:44:59 +0200 | [diff] [blame] | 761 | |
| 762 | |
Armin Ronacher | ba6e25a | 2008-11-02 15:58:14 +0100 | [diff] [blame] | 763 | class TemplateExpression(object): |
| 764 | """The :meth:`jinja2.Environment.compile_expression` method returns an |
| 765 | instance of this object. It encapsulates the expression-like access |
| 766 | to the template with an expression it wraps. |
| 767 | """ |
| 768 | |
| 769 | def __init__(self, template, undefined_to_none): |
| 770 | self._template = template |
| 771 | self._undefined_to_none = undefined_to_none |
| 772 | |
| 773 | def __call__(self, *args, **kwargs): |
| 774 | context = self._template.new_context(dict(*args, **kwargs)) |
| 775 | consume(self._template.root_render_func(context)) |
| 776 | rv = context.vars['result'] |
| 777 | if self._undefined_to_none and isinstance(rv, Undefined): |
| 778 | rv = None |
| 779 | return rv |
| 780 | |
| 781 | |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 782 | class TemplateStream(object): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 783 | """A template stream works pretty much like an ordinary python generator |
| 784 | but it can buffer multiple items to reduce the number of total iterations. |
| 785 | Per default the output is unbuffered which means that for every unbuffered |
| 786 | instruction in the template one unicode string is yielded. |
| 787 | |
| 788 | If buffering is enabled with a buffer size of 5, five items are combined |
| 789 | into a new unicode string. This is mainly useful if you are streaming |
| 790 | big templates to a client via WSGI which flushes after each iteration. |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 791 | """ |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 792 | |
| 793 | def __init__(self, gen): |
| 794 | self._gen = gen |
Armin Ronacher | 9cf9591 | 2008-05-24 19:54:43 +0200 | [diff] [blame] | 795 | self.disable_buffering() |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 796 | |
Armin Ronacher | 74b5106 | 2008-06-17 11:28:59 +0200 | [diff] [blame] | 797 | def dump(self, fp, encoding=None, errors='strict'): |
| 798 | """Dump the complete stream into a file or file-like object. |
| 799 | Per default unicode strings are written, if you want to encode |
| 800 | before writing specifiy an `encoding`. |
| 801 | |
| 802 | Example usage:: |
| 803 | |
| 804 | Template('Hello {{ name }}!').stream(name='foo').dump('hello.html') |
| 805 | """ |
| 806 | close = False |
| 807 | if isinstance(fp, basestring): |
| 808 | fp = file(fp, 'w') |
| 809 | close = True |
| 810 | try: |
| 811 | if encoding is not None: |
| 812 | iterable = (x.encode(encoding, errors) for x in self) |
| 813 | else: |
| 814 | iterable = self |
| 815 | if hasattr(fp, 'writelines'): |
| 816 | fp.writelines(iterable) |
| 817 | else: |
| 818 | for item in iterable: |
| 819 | fp.write(item) |
| 820 | finally: |
| 821 | if close: |
| 822 | fp.close() |
| 823 | |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 824 | def disable_buffering(self): |
| 825 | """Disable the output buffering.""" |
| 826 | self._next = self._gen.next |
| 827 | self.buffered = False |
| 828 | |
| 829 | def enable_buffering(self, size=5): |
Armin Ronacher | d134231 | 2008-04-28 12:20:12 +0200 | [diff] [blame] | 830 | """Enable buffering. Buffer `size` items before yielding them.""" |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 831 | if size <= 1: |
| 832 | raise ValueError('buffer size too small') |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 833 | |
Armin Ronacher | 5dfbfc1 | 2008-05-25 18:10:12 +0200 | [diff] [blame] | 834 | def generator(next): |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 835 | buf = [] |
| 836 | c_size = 0 |
| 837 | push = buf.append |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 838 | |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 839 | while 1: |
| 840 | try: |
Armin Ronacher | b5124e6 | 2008-04-25 00:36:14 +0200 | [diff] [blame] | 841 | while c_size < size: |
Armin Ronacher | 981cbf6 | 2008-05-13 09:12:27 +0200 | [diff] [blame] | 842 | c = next() |
| 843 | push(c) |
| 844 | if c: |
| 845 | c_size += 1 |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 846 | except StopIteration: |
| 847 | if not c_size: |
Armin Ronacher | d84ec46 | 2008-04-29 13:43:16 +0200 | [diff] [blame] | 848 | return |
Armin Ronacher | de6bf71 | 2008-04-26 01:44:14 +0200 | [diff] [blame] | 849 | yield concat(buf) |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 850 | del buf[:] |
| 851 | c_size = 0 |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 852 | |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 853 | self.buffered = True |
Armin Ronacher | 5dfbfc1 | 2008-05-25 18:10:12 +0200 | [diff] [blame] | 854 | self._next = generator(self._gen.next).next |
Armin Ronacher | c63243e | 2008-04-14 22:53:58 +0200 | [diff] [blame] | 855 | |
| 856 | def __iter__(self): |
| 857 | return self |
| 858 | |
| 859 | def next(self): |
| 860 | return self._next() |
Armin Ronacher | 203bfcb | 2008-04-24 21:54:44 +0200 | [diff] [blame] | 861 | |
| 862 | |
| 863 | # hook in default template class. if anyone reads this comment: ignore that |
| 864 | # it's possible to use custom templates ;-) |
| 865 | Environment.template_class = Template |