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