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