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