blob: 4b9ce6d635f1b8370cd4ea5cb01b140c4d263fd8 [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 Ronacher7ceced52008-05-03 10:15:31 +020014from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat
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 Ronacher19cf9c22008-05-01 12:49:53 +020019__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
20 'TemplateRuntimeError', 'missing', 'concat', 'escape',
Armin Ronacherd1342312008-04-28 12:20:12 +020021 'markup_join', 'unicode_join']
Armin Ronacher0611e492008-04-25 23:44:14 +020022
23
Armin Ronacherd1342312008-04-28 12:20:12 +020024def markup_join(*args):
25 """Concatenation that escapes if necessary and converts to unicode."""
26 buf = []
27 iterator = imap(soft_unicode, args)
28 for arg in iterator:
29 buf.append(arg)
30 if hasattr(arg, '__html__'):
31 return Markup(u'').join(chain(buf, iterator))
32 return concat(buf)
33
34
35def unicode_join(*args):
36 """Simple args to unicode conversion and concatenation."""
37 return concat(imap(unicode, args))
38
39
Armin Ronacher19cf9c22008-05-01 12:49:53 +020040class Context(object):
Armin Ronacher7259c762008-04-30 13:03:59 +020041 """The template context holds the variables of a template. It stores the
42 values passed to the template and also the names the template exports.
43 Creating instances is neither supported nor useful as it's created
44 automatically at various stages of the template evaluation and should not
45 be created by hand.
Armin Ronacherc9705c22008-04-27 21:28:03 +020046
Armin Ronacher7259c762008-04-30 13:03:59 +020047 The context is immutable. Modifications on :attr:`parent` **must not**
48 happen and modifications on :attr:`vars` are allowed from generated
49 template code only. Template filters and global functions marked as
50 :func:`contextfunction`\s get the active context passed as first argument
51 and are allowed to access the context read-only.
52
53 The template context supports read only dict operations (`get`,
54 `__getitem__`, `__contains__`) however `__getitem__` doesn't fail with
55 a `KeyError` but returns an :attr:`Undefined` object.
Armin Ronacher9706fab2008-04-08 18:49:56 +020056 """
Armin Ronachere791c2a2008-04-07 18:39:54 +020057
Armin Ronacher203bfcb2008-04-24 21:54:44 +020058 def __init__(self, environment, parent, name, blocks):
59 self.parent = parent
Armin Ronacher2feed1d2008-04-26 16:26:52 +020060 self.vars = vars = {}
Armin Ronacherc63243e2008-04-14 22:53:58 +020061 self.environment = environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020062 self.exported_vars = set()
Armin Ronacher68f77672008-04-17 11:50:39 +020063 self.name = name
Armin Ronacher203bfcb2008-04-24 21:54:44 +020064
65 # bind functions to the context of environment if required
Armin Ronacher2feed1d2008-04-26 16:26:52 +020066 for name, obj in parent.iteritems():
Armin Ronacher203bfcb2008-04-24 21:54:44 +020067 if type(obj) is FunctionType:
68 if getattr(obj, 'contextfunction', 0):
Armin Ronacher2feed1d2008-04-26 16:26:52 +020069 vars[name] = partial(obj, self)
Armin Ronacher203bfcb2008-04-24 21:54:44 +020070 elif getattr(obj, 'environmentfunction', 0):
Armin Ronacher2feed1d2008-04-26 16:26:52 +020071 vars[name] = partial(obj, environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +020072
73 # create the initial mapping of blocks. Whenever template inheritance
74 # takes place the runtime will update this mapping with the new blocks
75 # from the template.
Armin Ronacher75cfb862008-04-11 13:47:22 +020076 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
Armin Ronacherf059ec12008-04-11 22:21:00 +020077
Armin Ronacher203bfcb2008-04-24 21:54:44 +020078 def super(self, name, current):
Armin Ronacher62f8a292008-04-13 23:18:05 +020079 """Render a parent block."""
Armin Ronacherc9705c22008-04-27 21:28:03 +020080 try:
81 blocks = self.blocks[name]
82 pos = blocks.index(current) - 1
83 if pos < 0:
84 raise IndexError()
85 except LookupError:
Armin Ronacher9a822052008-04-17 18:44:07 +020086 return self.environment.undefined('there is no parent block '
Armin Ronacher19cf9c22008-05-01 12:49:53 +020087 'called %r.' % name,
88 name='super')
Armin Ronacherd1342312008-04-28 12:20:12 +020089 wrap = self.environment.autoescape and Markup or (lambda x: x)
90 render = lambda: wrap(concat(blocks[pos](self)))
Armin Ronacherc9705c22008-04-27 21:28:03 +020091 render.__name__ = render.name = name
92 return render
Armin Ronachere791c2a2008-04-07 18:39:54 +020093
Armin Ronacher53042292008-04-26 18:30:19 +020094 def get(self, key, default=None):
Armin Ronacher7259c762008-04-30 13:03:59 +020095 """Returns an item from the template context, if it doesn't exist
96 `default` is returned.
97 """
Armin Ronacher53042292008-04-26 18:30:19 +020098 if key in self.vars:
99 return self.vars[key]
100 if key in self.parent:
101 return self.parent[key]
102 return default
Armin Ronacherb5124e62008-04-25 00:36:14 +0200103
Armin Ronacher9706fab2008-04-08 18:49:56 +0200104 def get_exported(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200105 """Get a new dict with the exported variables."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200106 return dict((k, self.vars[k]) for k in self.exported_vars)
Armin Ronacher9706fab2008-04-08 18:49:56 +0200107
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200108 def get_all(self):
Armin Ronacher7259c762008-04-30 13:03:59 +0200109 """Return a copy of the complete context as dict including the
110 global variables.
111 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200112 return dict(self.parent, **self.vars)
113
Armin Ronacherb5124e62008-04-25 00:36:14 +0200114 def __contains__(self, name):
115 return name in self.vars or name in self.parent
116
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200117 def __getitem__(self, key):
118 if key in self.vars:
119 return self.vars[key]
Armin Ronacher53042292008-04-26 18:30:19 +0200120 if key in self.parent:
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200121 return self.parent[key]
Armin Ronacher53042292008-04-26 18:30:19 +0200122 return self.environment.undefined(name=key)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200123
Armin Ronacherf059ec12008-04-11 22:21:00 +0200124 def __repr__(self):
125 return '<%s %s of %r>' % (
126 self.__class__.__name__,
Armin Ronacher963f97d2008-04-25 11:44:59 +0200127 repr(self.get_all()),
Armin Ronacher68f77672008-04-17 11:50:39 +0200128 self.name
Armin Ronacherf059ec12008-04-11 22:21:00 +0200129 )
130
131
Armin Ronacherc9705c22008-04-27 21:28:03 +0200132class TemplateReference(object):
133 """The `self` in templates."""
Armin Ronacher62f8a292008-04-13 23:18:05 +0200134
Armin Ronacherc9705c22008-04-27 21:28:03 +0200135 def __init__(self, context):
136 self.__context = context
Armin Ronacher62f8a292008-04-13 23:18:05 +0200137
Armin Ronacherc9705c22008-04-27 21:28:03 +0200138 def __getitem__(self, name):
139 func = self.__context.blocks[name][-1]
Armin Ronacherd1342312008-04-28 12:20:12 +0200140 wrap = self.__context.environment.autoescape and \
141 Markup or (lambda x: x)
142 render = lambda: wrap(concat(func(self.__context)))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200143 render.__name__ = render.name = name
144 return render
Armin Ronacher62f8a292008-04-13 23:18:05 +0200145
146 def __repr__(self):
147 return '<%s %r>' % (
148 self.__class__.__name__,
Armin Ronacherc9705c22008-04-27 21:28:03 +0200149 self._context.name
Armin Ronacher62f8a292008-04-13 23:18:05 +0200150 )
151
152
Armin Ronacher32a910f2008-04-26 23:21:03 +0200153class LoopContext(object):
154 """A loop context for dynamic iteration."""
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200155
Armin Ronacher32a910f2008-04-26 23:21:03 +0200156 def __init__(self, iterable, enforce_length=False):
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200157 self._iterable = iterable
Armin Ronacher32a910f2008-04-26 23:21:03 +0200158 self._next = iter(iterable).next
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200159 self._length = None
Armin Ronacher32a910f2008-04-26 23:21:03 +0200160 self.index0 = -1
161 if enforce_length:
162 len(self)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200163
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200164 def cycle(self, *args):
165 """A replacement for the old ``{% cycle %}`` tag."""
166 if not args:
167 raise TypeError('no items for cycling given')
168 return args[self.index0 % len(args)]
169
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200170 first = property(lambda x: x.index0 == 0)
171 last = property(lambda x: x.revindex0 == 0)
172 index = property(lambda x: x.index0 + 1)
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200173 revindex = property(lambda x: x.length - x.index0)
174 revindex0 = property(lambda x: x.length - x.index)
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200175
176 def __len__(self):
177 return self.length
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200178
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200179 def __iter__(self):
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200180 return self
181
182 def next(self):
183 self.index0 += 1
184 return self._next(), self
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200185
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200186 @property
187 def length(self):
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200188 if self._length is None:
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200189 try:
190 length = len(self._iterable)
191 except TypeError:
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200192 self._iterable = tuple(self._iterable)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200193 self._next = iter(self._iterable).next
194 length = len(tuple(self._iterable)) + self.index0 + 1
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200195 self._length = length
196 return self._length
197
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200198 def __repr__(self):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200199 return '<%s %r/%r>' % (
200 self.__class__.__name__,
201 self.index,
202 self.length
203 )
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200204
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200205
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200206class Macro(object):
Armin Ronacherd55ab532008-04-09 16:13:39 +0200207 """Wraps a macro."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200208
Armin Ronacher963f97d2008-04-25 11:44:59 +0200209 def __init__(self, environment, func, name, arguments, defaults,
210 catch_kwargs, catch_varargs, caller):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200211 self._environment = environment
Armin Ronacher71082072008-04-12 14:19:36 +0200212 self._func = func
Armin Ronacherd84ec462008-04-29 13:43:16 +0200213 self._argument_count = len(arguments)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200214 self.name = name
215 self.arguments = arguments
216 self.defaults = defaults
Armin Ronacher963f97d2008-04-25 11:44:59 +0200217 self.catch_kwargs = catch_kwargs
218 self.catch_varargs = catch_varargs
Armin Ronacher71082072008-04-12 14:19:36 +0200219 self.caller = caller
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200220
221 def __call__(self, *args, **kwargs):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200222 arguments = []
Armin Ronacher9706fab2008-04-08 18:49:56 +0200223 for idx, name in enumerate(self.arguments):
224 try:
225 value = args[idx]
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200226 except:
Armin Ronacher9706fab2008-04-08 18:49:56 +0200227 try:
228 value = kwargs.pop(name)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200229 except:
Armin Ronacher9706fab2008-04-08 18:49:56 +0200230 try:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200231 value = self.defaults[idx - self._argument_count]
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200232 except:
Armin Ronacher9a822052008-04-17 18:44:07 +0200233 value = self._environment.undefined(
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200234 'parameter %r was not provided' % name, name=name)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200235 arguments.append(value)
236
237 # it's important that the order of these arguments does not change
238 # if not also changed in the compiler's `function_scoping` method.
239 # the order is caller, keyword arguments, positional arguments!
Armin Ronacher71082072008-04-12 14:19:36 +0200240 if self.caller:
241 caller = kwargs.pop('caller', None)
242 if caller is None:
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200243 caller = self._environment.undefined('No caller defined',
244 name='caller')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200245 arguments.append(caller)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200246 if self.catch_kwargs:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200247 arguments.append(kwargs)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200248 elif kwargs:
249 raise TypeError('macro %r takes no keyword argument %r' %
250 (self.name, iter(kwargs).next()))
251 if self.catch_varargs:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200252 arguments.append(args[self._argument_count:])
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200253 elif len(args) > self._argument_count:
254 raise TypeError('macro %r takes not more than %d argument(s)' %
255 (self.name, len(self.arguments)))
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200256 return self._func(*arguments)
Armin Ronacher71082072008-04-12 14:19:36 +0200257
258 def __repr__(self):
259 return '<%s %s>' % (
260 self.__class__.__name__,
261 self.name is None and 'anonymous' or repr(self.name)
262 )
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200263
264
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200265def fail_with_undefined_error(self, *args, **kwargs):
266 """Regular callback function for undefined objects that raises an
267 `UndefinedError` on call.
268 """
269 if self._undefined_hint is None:
270 if self._undefined_obj is None:
271 hint = '%r is undefined' % self._undefined_name
272 elif not isinstance(self._undefined_name, basestring):
273 hint = '%r object has no element %r' % (
274 self._undefined_obj.__class__.__name__,
275 self._undefined_name
276 )
277 else:
278 hint = '%r object has no attribute %r' % (
279 self._undefined_obj.__class__.__name__,
280 self._undefined_name
281 )
282 else:
283 hint = self._undefined_hint
284 raise UndefinedError(hint)
285
286
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200287class Undefined(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200288 """The default undefined type. This undefined type can be printed and
289 iterated over, but every other access will raise an :exc:`UndefinedError`:
290
291 >>> foo = Undefined(name='foo')
292 >>> str(foo)
293 ''
294 >>> not foo
295 True
296 >>> foo + 42
297 Traceback (most recent call last):
298 ...
299 jinja2.exceptions.UndefinedError: 'foo' is undefined
Armin Ronacherc63243e2008-04-14 22:53:58 +0200300 """
Armin Ronacher53042292008-04-26 18:30:19 +0200301 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200302
Armin Ronacher9a822052008-04-17 18:44:07 +0200303 def __init__(self, hint=None, obj=None, name=None):
304 self._undefined_hint = hint
305 self._undefined_obj = obj
306 self._undefined_name = name
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200307
Armin Ronacherc63243e2008-04-14 22:53:58 +0200308 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
309 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \
310 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
Armin Ronacher53042292008-04-26 18:30:19 +0200311 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
312 fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200313
314 def __str__(self):
315 return self.__unicode__().encode('utf-8')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200316
317 def __repr__(self):
Priit Laes4149a0e2008-04-17 19:04:44 +0200318 return 'Undefined'
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200319
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200320 def __unicode__(self):
321 return u''
322
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200323 def __len__(self):
324 return 0
325
326 def __iter__(self):
327 if 0:
328 yield None
Armin Ronacherc63243e2008-04-14 22:53:58 +0200329
330 def __nonzero__(self):
331 return False
332
333
334class DebugUndefined(Undefined):
Armin Ronacherd1342312008-04-28 12:20:12 +0200335 """An undefined that returns the debug info when printed.
336
337 >>> foo = DebugUndefined(name='foo')
338 >>> str(foo)
339 '{{ foo }}'
340 >>> not foo
341 True
342 >>> foo + 42
343 Traceback (most recent call last):
344 ...
345 jinja2.exceptions.UndefinedError: 'foo' is undefined
346 """
Armin Ronacher53042292008-04-26 18:30:19 +0200347 __slots__ = ()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200348
349 def __unicode__(self):
Armin Ronacher9a822052008-04-17 18:44:07 +0200350 if self._undefined_hint is None:
351 if self._undefined_obj is None:
352 return u'{{ %s }}' % self._undefined_name
353 return '{{ no such element: %s[%r] }}' % (
354 self._undefined_obj.__class__.__name__,
355 self._undefined_name
356 )
357 return u'{{ undefined value printed: %s }}' % self._undefined_hint
Armin Ronacherc63243e2008-04-14 22:53:58 +0200358
359
360class StrictUndefined(Undefined):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200361 """An undefined that barks on print and iteration as well as boolean
Armin Ronacher53042292008-04-26 18:30:19 +0200362 tests and all kinds of comparisons. In other words: you can do nothing
363 with it except checking if it's defined using the `defined` test.
Armin Ronacherd1342312008-04-28 12:20:12 +0200364
365 >>> foo = StrictUndefined(name='foo')
366 >>> str(foo)
367 Traceback (most recent call last):
368 ...
369 jinja2.exceptions.UndefinedError: 'foo' is undefined
370 >>> not foo
371 Traceback (most recent call last):
372 ...
373 jinja2.exceptions.UndefinedError: 'foo' is undefined
374 >>> foo + 42
375 Traceback (most recent call last):
376 ...
377 jinja2.exceptions.UndefinedError: 'foo' is undefined
Priit Laes4149a0e2008-04-17 19:04:44 +0200378 """
Armin Ronacher53042292008-04-26 18:30:19 +0200379 __slots__ = ()
380 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
381 fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200382
Armin Ronacher53042292008-04-26 18:30:19 +0200383
384# remove remaining slots attributes, after the metaclass did the magic they
385# are unneeded and irritating as they contain wrong data for the subclasses.
386del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__