blob: 5233210f5bf41cc409e87539929f5f3f1c3322eb [file] [log] [blame]
Armin Ronachere791c2a2008-04-07 18:39:54 +02001# -*- coding: utf-8 -*-
2"""
3 jinja2.runtime
4 ~~~~~~~~~~~~~~
5
6 Runtime helpers.
7
8 :copyright: Copyright 2008 by Armin Ronacher.
9 :license: GNU GPL.
10"""
Armin Ronacher1ae4fdf2008-04-28 20:49:51 +020011import sys
Armin Ronacher4f7d2d52008-04-22 10:40:26 +020012from types import FunctionType
Armin Ronacherd1342312008-04-28 12:20:12 +020013from itertools import chain, imap
Armin Ronacher7259c762008-04-30 13:03:59 +020014from jinja2.utils import Markup, partial, soft_unicode, escape, missing
Armin Ronacherd1342312008-04-28 12:20:12 +020015from jinja2.exceptions import UndefinedError, TemplateRuntimeError
Armin Ronachere791c2a2008-04-07 18:39:54 +020016
17
Armin Ronacher2feed1d2008-04-26 16:26:52 +020018# these variables are exported to the template runtime
Armin Ronacherc9705c22008-04-27 21:28:03 +020019__all__ = ['LoopContext', 'TemplateContext', 'TemplateReference', 'Macro',
Armin Ronacherd1342312008-04-28 12:20:12 +020020 'TemplateRuntimeError', 'Markup', 'missing', 'concat', 'escape',
21 'markup_join', 'unicode_join']
Armin Ronacher0611e492008-04-25 23:44:14 +020022
23
Armin Ronacherde6bf712008-04-26 01:44:14 +020024# concatenate a list of strings and convert them to unicode.
Armin Ronacher1ae4fdf2008-04-28 20:49:51 +020025# unfortunately there is a bug in python 2.4 and lower that causes
26# unicode.join trash the traceback.
27try:
28 def _test_gen_bug():
29 raise TypeError(_test_gen_bug)
30 yield None
31 u''.join(_test_gen_bug())
Armin Ronacher7259c762008-04-30 13:03:59 +020032except TypeError, _error:
33 if _error.args and _error.args[0] is _test_gen_bug:
Armin Ronacher1ae4fdf2008-04-28 20:49:51 +020034 concat = u''.join
35 else:
36 def concat(gen):
37 try:
Armin Ronacherd84ec462008-04-29 13:43:16 +020038 return u''.join(list(gen))
Armin Ronacher1ae4fdf2008-04-28 20:49:51 +020039 except:
40 exc_type, exc_value, tb = sys.exc_info()
41 raise exc_type, exc_value, tb.tb_next
Armin Ronacher7259c762008-04-30 13:03:59 +020042 del _test_gen_bug, _error
Armin Ronacherde6bf712008-04-26 01:44:14 +020043
44
Armin Ronacherd1342312008-04-28 12:20:12 +020045def markup_join(*args):
46 """Concatenation that escapes if necessary and converts to unicode."""
47 buf = []
48 iterator = imap(soft_unicode, args)
49 for arg in iterator:
50 buf.append(arg)
51 if hasattr(arg, '__html__'):
52 return Markup(u'').join(chain(buf, iterator))
53 return concat(buf)
54
55
56def unicode_join(*args):
57 """Simple args to unicode conversion and concatenation."""
58 return concat(imap(unicode, args))
59
60
Armin Ronacher203bfcb2008-04-24 21:54:44 +020061class TemplateContext(object):
Armin Ronacher7259c762008-04-30 13:03:59 +020062 """The template context holds the variables of a template. It stores the
63 values passed to the template and also the names the template exports.
64 Creating instances is neither supported nor useful as it's created
65 automatically at various stages of the template evaluation and should not
66 be created by hand.
Armin Ronacherc9705c22008-04-27 21:28:03 +020067
Armin Ronacher7259c762008-04-30 13:03:59 +020068 The context is immutable. Modifications on :attr:`parent` **must not**
69 happen and modifications on :attr:`vars` are allowed from generated
70 template code only. Template filters and global functions marked as
71 :func:`contextfunction`\s get the active context passed as first argument
72 and are allowed to access the context read-only.
73
74 The template context supports read only dict operations (`get`,
75 `__getitem__`, `__contains__`) however `__getitem__` doesn't fail with
76 a `KeyError` but returns an :attr:`Undefined` object.
Armin Ronacher9706fab2008-04-08 18:49:56 +020077 """
Armin Ronachere791c2a2008-04-07 18:39:54 +020078
Armin Ronacher203bfcb2008-04-24 21:54:44 +020079 def __init__(self, environment, parent, name, blocks):
80 self.parent = parent
Armin Ronacher2feed1d2008-04-26 16:26:52 +020081 self.vars = vars = {}
Armin Ronacherc63243e2008-04-14 22:53:58 +020082 self.environment = environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020083 self.exported_vars = set()
Armin Ronacher68f77672008-04-17 11:50:39 +020084 self.name = name
Armin Ronacher203bfcb2008-04-24 21:54:44 +020085
86 # bind functions to the context of environment if required
Armin Ronacher2feed1d2008-04-26 16:26:52 +020087 for name, obj in parent.iteritems():
Armin Ronacher203bfcb2008-04-24 21:54:44 +020088 if type(obj) is FunctionType:
89 if getattr(obj, 'contextfunction', 0):
Armin Ronacher2feed1d2008-04-26 16:26:52 +020090 vars[name] = partial(obj, self)
Armin Ronacher203bfcb2008-04-24 21:54:44 +020091 elif getattr(obj, 'environmentfunction', 0):
Armin Ronacher2feed1d2008-04-26 16:26:52 +020092 vars[name] = partial(obj, environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +020093
94 # create the initial mapping of blocks. Whenever template inheritance
95 # takes place the runtime will update this mapping with the new blocks
96 # from the template.
Armin Ronacher75cfb862008-04-11 13:47:22 +020097 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
Armin Ronacherf059ec12008-04-11 22:21:00 +020098
Armin Ronacher203bfcb2008-04-24 21:54:44 +020099 def super(self, name, current):
Armin Ronacher62f8a292008-04-13 23:18:05 +0200100 """Render a parent block."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200101 try:
102 blocks = self.blocks[name]
103 pos = blocks.index(current) - 1
104 if pos < 0:
105 raise IndexError()
106 except LookupError:
Armin Ronacher9a822052008-04-17 18:44:07 +0200107 return self.environment.undefined('there is no parent block '
Armin Ronacherc9705c22008-04-27 21:28:03 +0200108 'called %r.' % name)
Armin Ronacherd1342312008-04-28 12:20:12 +0200109 wrap = self.environment.autoescape and Markup or (lambda x: x)
110 render = lambda: wrap(concat(blocks[pos](self)))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200111 render.__name__ = render.name = name
112 return render
Armin Ronachere791c2a2008-04-07 18:39:54 +0200113
Armin Ronacher53042292008-04-26 18:30:19 +0200114 def get(self, key, default=None):
Armin Ronacher7259c762008-04-30 13:03:59 +0200115 """Returns an item from the template context, if it doesn't exist
116 `default` is returned.
117 """
Armin Ronacher53042292008-04-26 18:30:19 +0200118 if key in self.vars:
119 return self.vars[key]
120 if key in self.parent:
121 return self.parent[key]
122 return default
Armin Ronacherb5124e62008-04-25 00:36:14 +0200123
Armin Ronacher9706fab2008-04-08 18:49:56 +0200124 def get_exported(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200125 """Get a new dict with the exported variables."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200126 return dict((k, self.vars[k]) for k in self.exported_vars)
Armin Ronacher9706fab2008-04-08 18:49:56 +0200127
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200128 def get_all(self):
Armin Ronacher7259c762008-04-30 13:03:59 +0200129 """Return a copy of the complete context as dict including the
130 global variables.
131 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200132 return dict(self.parent, **self.vars)
133
Armin Ronacherb5124e62008-04-25 00:36:14 +0200134 def __contains__(self, name):
135 return name in self.vars or name in self.parent
136
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200137 def __getitem__(self, key):
138 if key in self.vars:
139 return self.vars[key]
Armin Ronacher53042292008-04-26 18:30:19 +0200140 if key in self.parent:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200141 return self.parent[key]
Armin Ronacher53042292008-04-26 18:30:19 +0200142 return self.environment.undefined(name=key)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200143
Armin Ronacherf059ec12008-04-11 22:21:00 +0200144 def __repr__(self):
145 return '<%s %s of %r>' % (
146 self.__class__.__name__,
Armin Ronacher963f97d2008-04-25 11:44:59 +0200147 repr(self.get_all()),
Armin Ronacher68f77672008-04-17 11:50:39 +0200148 self.name
Armin Ronacherf059ec12008-04-11 22:21:00 +0200149 )
150
151
Armin Ronacherc9705c22008-04-27 21:28:03 +0200152class TemplateReference(object):
153 """The `self` in templates."""
Armin Ronacher62f8a292008-04-13 23:18:05 +0200154
Armin Ronacherc9705c22008-04-27 21:28:03 +0200155 def __init__(self, context):
156 self.__context = context
Armin Ronacher62f8a292008-04-13 23:18:05 +0200157
Armin Ronacherc9705c22008-04-27 21:28:03 +0200158 def __getitem__(self, name):
159 func = self.__context.blocks[name][-1]
Armin Ronacherd1342312008-04-28 12:20:12 +0200160 wrap = self.__context.environment.autoescape and \
161 Markup or (lambda x: x)
162 render = lambda: wrap(concat(func(self.__context)))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200163 render.__name__ = render.name = name
164 return render
Armin Ronacher62f8a292008-04-13 23:18:05 +0200165
166 def __repr__(self):
167 return '<%s %r>' % (
168 self.__class__.__name__,
Armin Ronacherc9705c22008-04-27 21:28:03 +0200169 self._context.name
Armin Ronacher62f8a292008-04-13 23:18:05 +0200170 )
171
172
Armin Ronacher32a910f2008-04-26 23:21:03 +0200173class LoopContext(object):
174 """A loop context for dynamic iteration."""
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200175
Armin Ronacher32a910f2008-04-26 23:21:03 +0200176 def __init__(self, iterable, enforce_length=False):
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200177 self._iterable = iterable
Armin Ronacher32a910f2008-04-26 23:21:03 +0200178 self._next = iter(iterable).next
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200179 self._length = None
Armin Ronacher32a910f2008-04-26 23:21:03 +0200180 self.index0 = -1
181 if enforce_length:
182 len(self)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200183
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200184 def cycle(self, *args):
185 """A replacement for the old ``{% cycle %}`` tag."""
186 if not args:
187 raise TypeError('no items for cycling given')
188 return args[self.index0 % len(args)]
189
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200190 first = property(lambda x: x.index0 == 0)
191 last = property(lambda x: x.revindex0 == 0)
192 index = property(lambda x: x.index0 + 1)
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200193 revindex = property(lambda x: x.length - x.index0)
194 revindex0 = property(lambda x: x.length - x.index)
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200195
196 def __len__(self):
197 return self.length
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200198
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200199 def __iter__(self):
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200200 return self
201
202 def next(self):
203 self.index0 += 1
204 return self._next(), self
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200205
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200206 @property
207 def length(self):
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200208 if self._length is None:
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200209 try:
210 length = len(self._iterable)
211 except TypeError:
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200212 self._iterable = tuple(self._iterable)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200213 self._next = iter(self._iterable).next
214 length = len(tuple(self._iterable)) + self.index0 + 1
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200215 self._length = length
216 return self._length
217
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200218 def __repr__(self):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200219 return '<%s %r/%r>' % (
220 self.__class__.__name__,
221 self.index,
222 self.length
223 )
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200224
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200225
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200226class Macro(object):
Armin Ronacherd55ab532008-04-09 16:13:39 +0200227 """Wraps a macro."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200228
Armin Ronacher963f97d2008-04-25 11:44:59 +0200229 def __init__(self, environment, func, name, arguments, defaults,
230 catch_kwargs, catch_varargs, caller):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200231 self._environment = environment
Armin Ronacher71082072008-04-12 14:19:36 +0200232 self._func = func
Armin Ronacherd84ec462008-04-29 13:43:16 +0200233 self._argument_count = len(arguments)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200234 self.name = name
235 self.arguments = arguments
236 self.defaults = defaults
Armin Ronacher963f97d2008-04-25 11:44:59 +0200237 self.catch_kwargs = catch_kwargs
238 self.catch_varargs = catch_varargs
Armin Ronacher71082072008-04-12 14:19:36 +0200239 self.caller = caller
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200240
241 def __call__(self, *args, **kwargs):
Armin Ronacherd84ec462008-04-29 13:43:16 +0200242 if not self.catch_varargs and len(args) > self._argument_count:
Armin Ronacher963f97d2008-04-25 11:44:59 +0200243 raise TypeError('macro %r takes not more than %d argument(s)' %
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200244 (self.name, len(self.arguments)))
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200245 arguments = []
Armin Ronacher9706fab2008-04-08 18:49:56 +0200246 for idx, name in enumerate(self.arguments):
247 try:
248 value = args[idx]
249 except IndexError:
250 try:
251 value = kwargs.pop(name)
252 except KeyError:
253 try:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200254 value = self.defaults[idx - self._argument_count]
Armin Ronacher9706fab2008-04-08 18:49:56 +0200255 except IndexError:
Armin Ronacher9a822052008-04-17 18:44:07 +0200256 value = self._environment.undefined(
257 'parameter %r was not provided' % name)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200258 arguments.append(value)
259
260 # it's important that the order of these arguments does not change
261 # if not also changed in the compiler's `function_scoping` method.
262 # the order is caller, keyword arguments, positional arguments!
Armin Ronacher71082072008-04-12 14:19:36 +0200263 if self.caller:
264 caller = kwargs.pop('caller', None)
265 if caller is None:
Armin Ronacher9a822052008-04-17 18:44:07 +0200266 caller = self._environment.undefined('No caller defined')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200267 arguments.append(caller)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200268 if self.catch_kwargs:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200269 arguments.append(kwargs)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200270 elif kwargs:
271 raise TypeError('macro %r takes no keyword argument %r' %
272 (self.name, iter(kwargs).next()))
273 if self.catch_varargs:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200274 arguments.append(args[self._argument_count:])
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200275 return self._func(*arguments)
Armin Ronacher71082072008-04-12 14:19:36 +0200276
277 def __repr__(self):
278 return '<%s %s>' % (
279 self.__class__.__name__,
280 self.name is None and 'anonymous' or repr(self.name)
281 )
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200282
283
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200284def fail_with_undefined_error(self, *args, **kwargs):
285 """Regular callback function for undefined objects that raises an
286 `UndefinedError` on call.
287 """
288 if self._undefined_hint is None:
289 if self._undefined_obj is None:
290 hint = '%r is undefined' % self._undefined_name
291 elif not isinstance(self._undefined_name, basestring):
292 hint = '%r object has no element %r' % (
293 self._undefined_obj.__class__.__name__,
294 self._undefined_name
295 )
296 else:
297 hint = '%r object has no attribute %r' % (
298 self._undefined_obj.__class__.__name__,
299 self._undefined_name
300 )
301 else:
302 hint = self._undefined_hint
303 raise UndefinedError(hint)
304
305
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200306class Undefined(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200307 """The default undefined type. This undefined type can be printed and
308 iterated over, but every other access will raise an :exc:`UndefinedError`:
309
310 >>> foo = Undefined(name='foo')
311 >>> str(foo)
312 ''
313 >>> not foo
314 True
315 >>> foo + 42
316 Traceback (most recent call last):
317 ...
318 jinja2.exceptions.UndefinedError: 'foo' is undefined
Armin Ronacherc63243e2008-04-14 22:53:58 +0200319 """
Armin Ronacher53042292008-04-26 18:30:19 +0200320 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200321
Armin Ronacher9a822052008-04-17 18:44:07 +0200322 def __init__(self, hint=None, obj=None, name=None):
323 self._undefined_hint = hint
324 self._undefined_obj = obj
325 self._undefined_name = name
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200326
Armin Ronacherc63243e2008-04-14 22:53:58 +0200327 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
328 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \
329 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
Armin Ronacher53042292008-04-26 18:30:19 +0200330 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
331 fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200332
333 def __str__(self):
334 return self.__unicode__().encode('utf-8')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200335
336 def __repr__(self):
Priit Laes4149a0e2008-04-17 19:04:44 +0200337 return 'Undefined'
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200338
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200339 def __unicode__(self):
340 return u''
341
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200342 def __len__(self):
343 return 0
344
345 def __iter__(self):
346 if 0:
347 yield None
Armin Ronacherc63243e2008-04-14 22:53:58 +0200348
349 def __nonzero__(self):
350 return False
351
352
353class DebugUndefined(Undefined):
Armin Ronacherd1342312008-04-28 12:20:12 +0200354 """An undefined that returns the debug info when printed.
355
356 >>> foo = DebugUndefined(name='foo')
357 >>> str(foo)
358 '{{ foo }}'
359 >>> not foo
360 True
361 >>> foo + 42
362 Traceback (most recent call last):
363 ...
364 jinja2.exceptions.UndefinedError: 'foo' is undefined
365 """
Armin Ronacher53042292008-04-26 18:30:19 +0200366 __slots__ = ()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200367
368 def __unicode__(self):
Armin Ronacher9a822052008-04-17 18:44:07 +0200369 if self._undefined_hint is None:
370 if self._undefined_obj is None:
371 return u'{{ %s }}' % self._undefined_name
372 return '{{ no such element: %s[%r] }}' % (
373 self._undefined_obj.__class__.__name__,
374 self._undefined_name
375 )
376 return u'{{ undefined value printed: %s }}' % self._undefined_hint
Armin Ronacherc63243e2008-04-14 22:53:58 +0200377
378
379class StrictUndefined(Undefined):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200380 """An undefined that barks on print and iteration as well as boolean
Armin Ronacher53042292008-04-26 18:30:19 +0200381 tests and all kinds of comparisons. In other words: you can do nothing
382 with it except checking if it's defined using the `defined` test.
Armin Ronacherd1342312008-04-28 12:20:12 +0200383
384 >>> foo = StrictUndefined(name='foo')
385 >>> str(foo)
386 Traceback (most recent call last):
387 ...
388 jinja2.exceptions.UndefinedError: 'foo' is undefined
389 >>> not foo
390 Traceback (most recent call last):
391 ...
392 jinja2.exceptions.UndefinedError: 'foo' is undefined
393 >>> foo + 42
394 Traceback (most recent call last):
395 ...
396 jinja2.exceptions.UndefinedError: 'foo' is undefined
Priit Laes4149a0e2008-04-17 19:04:44 +0200397 """
Armin Ronacher53042292008-04-26 18:30:19 +0200398 __slots__ = ()
399 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
400 fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200401
Armin Ronacher53042292008-04-26 18:30:19 +0200402
403# remove remaining slots attributes, after the metaclass did the magic they
404# are unneeded and irritating as they contain wrong data for the subclasses.
405del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__