blob: d734182c3450abafbbcd4681cd123fa9eed4f10e [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`,
Armin Ronacherf35e2812008-05-06 16:04:10 +020054 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
55 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
56 method that doesn't fail with a `KeyError` but returns an
57 :class:`Undefined` object for missing variables.
Armin Ronacher9706fab2008-04-08 18:49:56 +020058 """
Armin Ronachere791c2a2008-04-07 18:39:54 +020059
Armin Ronacher203bfcb2008-04-24 21:54:44 +020060 def __init__(self, environment, parent, name, blocks):
61 self.parent = parent
Armin Ronacher2feed1d2008-04-26 16:26:52 +020062 self.vars = vars = {}
Armin Ronacherc63243e2008-04-14 22:53:58 +020063 self.environment = environment
Armin Ronacher203bfcb2008-04-24 21:54:44 +020064 self.exported_vars = set()
Armin Ronacher68f77672008-04-17 11:50:39 +020065 self.name = name
Armin Ronacher203bfcb2008-04-24 21:54:44 +020066
67 # bind functions to the context of environment if required
Armin Ronacher2feed1d2008-04-26 16:26:52 +020068 for name, obj in parent.iteritems():
Armin Ronacher203bfcb2008-04-24 21:54:44 +020069 if type(obj) is FunctionType:
70 if getattr(obj, 'contextfunction', 0):
Armin Ronacher2feed1d2008-04-26 16:26:52 +020071 vars[name] = partial(obj, self)
Armin Ronacher203bfcb2008-04-24 21:54:44 +020072 elif getattr(obj, 'environmentfunction', 0):
Armin Ronacher2feed1d2008-04-26 16:26:52 +020073 vars[name] = partial(obj, environment)
Armin Ronacher203bfcb2008-04-24 21:54:44 +020074
75 # create the initial mapping of blocks. Whenever template inheritance
76 # takes place the runtime will update this mapping with the new blocks
77 # from the template.
Armin Ronacher75cfb862008-04-11 13:47:22 +020078 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
Armin Ronacherf059ec12008-04-11 22:21:00 +020079
Armin Ronacher203bfcb2008-04-24 21:54:44 +020080 def super(self, name, current):
Armin Ronacher62f8a292008-04-13 23:18:05 +020081 """Render a parent block."""
Armin Ronacherc9705c22008-04-27 21:28:03 +020082 try:
83 blocks = self.blocks[name]
84 pos = blocks.index(current) - 1
85 if pos < 0:
86 raise IndexError()
87 except LookupError:
Armin Ronacher9a822052008-04-17 18:44:07 +020088 return self.environment.undefined('there is no parent block '
Armin Ronacher19cf9c22008-05-01 12:49:53 +020089 'called %r.' % name,
90 name='super')
Armin Ronacherd1342312008-04-28 12:20:12 +020091 wrap = self.environment.autoescape and Markup or (lambda x: x)
92 render = lambda: wrap(concat(blocks[pos](self)))
Armin Ronacherc9705c22008-04-27 21:28:03 +020093 render.__name__ = render.name = name
94 return render
Armin Ronachere791c2a2008-04-07 18:39:54 +020095
Armin Ronacher53042292008-04-26 18:30:19 +020096 def get(self, key, default=None):
Armin Ronacher7259c762008-04-30 13:03:59 +020097 """Returns an item from the template context, if it doesn't exist
98 `default` is returned.
99 """
Armin Ronacherf35e2812008-05-06 16:04:10 +0200100 try:
101 return self[key]
102 except KeyError:
103 return default
104
105 def resolve(self, key):
106 """Looks up a variable like `__getitem__` or `get` but returns an
107 :class:`Undefined` object with the name of the name looked up.
108 """
Armin Ronacher53042292008-04-26 18:30:19 +0200109 if key in self.vars:
110 return self.vars[key]
111 if key in self.parent:
112 return self.parent[key]
Armin Ronacherf35e2812008-05-06 16:04:10 +0200113 return self.environment.undefined(name=key)
Armin Ronacherb5124e62008-04-25 00:36:14 +0200114
Armin Ronacher9706fab2008-04-08 18:49:56 +0200115 def get_exported(self):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200116 """Get a new dict with the exported variables."""
Armin Ronacherc9705c22008-04-27 21:28:03 +0200117 return dict((k, self.vars[k]) for k in self.exported_vars)
Armin Ronacher9706fab2008-04-08 18:49:56 +0200118
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200119 def get_all(self):
Armin Ronacher7259c762008-04-30 13:03:59 +0200120 """Return a copy of the complete context as dict including the
121 global variables.
122 """
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200123 return dict(self.parent, **self.vars)
124
Armin Ronacherf35e2812008-05-06 16:04:10 +0200125 def _all(meth):
126 def proxy(self):
127 return getattr(self.get_all(), meth)()
128 proxy.__doc__ = getattr(dict, meth).__doc__
129 proxy.__name__ = meth
130 return proxy
131
132 keys = _all('keys')
133 values = _all('values')
134 items = _all('items')
135 iterkeys = _all('iterkeys')
136 itervalues = _all('itervalues')
137 iteritems = _all('iteritems')
138 del _all
139
Armin Ronacherb5124e62008-04-25 00:36:14 +0200140 def __contains__(self, name):
141 return name in self.vars or name in self.parent
142
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200143 def __getitem__(self, key):
Armin Ronacherf35e2812008-05-06 16:04:10 +0200144 """Lookup a variable or raise `KeyError`."""
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200145 if key in self.vars:
146 return self.vars[key]
Armin Ronacherf35e2812008-05-06 16:04:10 +0200147 return self.parent[key]
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200148
Armin Ronacherf059ec12008-04-11 22:21:00 +0200149 def __repr__(self):
150 return '<%s %s of %r>' % (
151 self.__class__.__name__,
Armin Ronacher963f97d2008-04-25 11:44:59 +0200152 repr(self.get_all()),
Armin Ronacher68f77672008-04-17 11:50:39 +0200153 self.name
Armin Ronacherf059ec12008-04-11 22:21:00 +0200154 )
155
156
Armin Ronacherc9705c22008-04-27 21:28:03 +0200157class TemplateReference(object):
158 """The `self` in templates."""
Armin Ronacher62f8a292008-04-13 23:18:05 +0200159
Armin Ronacherc9705c22008-04-27 21:28:03 +0200160 def __init__(self, context):
161 self.__context = context
Armin Ronacher62f8a292008-04-13 23:18:05 +0200162
Armin Ronacherc9705c22008-04-27 21:28:03 +0200163 def __getitem__(self, name):
164 func = self.__context.blocks[name][-1]
Armin Ronacherd1342312008-04-28 12:20:12 +0200165 wrap = self.__context.environment.autoescape and \
166 Markup or (lambda x: x)
167 render = lambda: wrap(concat(func(self.__context)))
Armin Ronacherc9705c22008-04-27 21:28:03 +0200168 render.__name__ = render.name = name
169 return render
Armin Ronacher62f8a292008-04-13 23:18:05 +0200170
171 def __repr__(self):
172 return '<%s %r>' % (
173 self.__class__.__name__,
Armin Ronacherc9705c22008-04-27 21:28:03 +0200174 self._context.name
Armin Ronacher62f8a292008-04-13 23:18:05 +0200175 )
176
177
Armin Ronacher32a910f2008-04-26 23:21:03 +0200178class LoopContext(object):
179 """A loop context for dynamic iteration."""
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200180
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200181 def __init__(self, iterable, enforce_length=False, recurse=None):
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200182 self._iterable = iterable
Armin Ronacher32a910f2008-04-26 23:21:03 +0200183 self._next = iter(iterable).next
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200184 self._length = None
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200185 self._recurse = recurse
Armin Ronacher32a910f2008-04-26 23:21:03 +0200186 self.index0 = -1
187 if enforce_length:
188 len(self)
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200189
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200190 def cycle(self, *args):
191 """A replacement for the old ``{% cycle %}`` tag."""
192 if not args:
193 raise TypeError('no items for cycling given')
194 return args[self.index0 % len(args)]
195
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200196 first = property(lambda x: x.index0 == 0)
197 last = property(lambda x: x.revindex0 == 0)
198 index = property(lambda x: x.index0 + 1)
Armin Ronacher10f3ba22008-04-18 11:30:37 +0200199 revindex = property(lambda x: x.length - x.index0)
200 revindex0 = property(lambda x: x.length - x.index)
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200201
202 def __len__(self):
203 return self.length
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200204
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200205 def __iter__(self):
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200206 return self
207
Armin Ronacher1e1e8902008-05-11 23:21:16 +0200208 def __call__(self, iterable):
209 if self._recurse is None:
210 raise TypeError('Tried to call non recursive loop. Maybe you '
211 'forgot the "recursive" keyword.')
212 return self._recurse(iterable, self._recurse)
213
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200214 def next(self):
215 self.index0 += 1
216 return self._next(), self
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200217
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200218 @property
219 def length(self):
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200220 if self._length is None:
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200221 try:
222 length = len(self._iterable)
223 except TypeError:
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200224 self._iterable = tuple(self._iterable)
Armin Ronacher3d8b7842008-04-13 13:16:50 +0200225 self._next = iter(self._iterable).next
226 length = len(tuple(self._iterable)) + self.index0 + 1
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200227 self._length = length
228 return self._length
229
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200230 def __repr__(self):
Armin Ronacherc9705c22008-04-27 21:28:03 +0200231 return '<%s %r/%r>' % (
232 self.__class__.__name__,
233 self.index,
234 self.length
235 )
Armin Ronacher2e9396b2008-04-16 14:21:57 +0200236
Armin Ronacher180a1bd2008-04-09 12:14:24 +0200237
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200238class Macro(object):
Armin Ronacherd55ab532008-04-09 16:13:39 +0200239 """Wraps a macro."""
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200240
Armin Ronacher963f97d2008-04-25 11:44:59 +0200241 def __init__(self, environment, func, name, arguments, defaults,
242 catch_kwargs, catch_varargs, caller):
Armin Ronacherc63243e2008-04-14 22:53:58 +0200243 self._environment = environment
Armin Ronacher71082072008-04-12 14:19:36 +0200244 self._func = func
Armin Ronacherd84ec462008-04-29 13:43:16 +0200245 self._argument_count = len(arguments)
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200246 self.name = name
247 self.arguments = arguments
248 self.defaults = defaults
Armin Ronacher963f97d2008-04-25 11:44:59 +0200249 self.catch_kwargs = catch_kwargs
250 self.catch_varargs = catch_varargs
Armin Ronacher71082072008-04-12 14:19:36 +0200251 self.caller = caller
Armin Ronacher4f62a9f2008-04-08 18:09:13 +0200252
253 def __call__(self, *args, **kwargs):
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200254 arguments = []
Armin Ronacher9706fab2008-04-08 18:49:56 +0200255 for idx, name in enumerate(self.arguments):
256 try:
257 value = args[idx]
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200258 except:
Armin Ronacher9706fab2008-04-08 18:49:56 +0200259 try:
260 value = kwargs.pop(name)
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200261 except:
Armin Ronacher9706fab2008-04-08 18:49:56 +0200262 try:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200263 value = self.defaults[idx - self._argument_count]
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200264 except:
Armin Ronacher9a822052008-04-17 18:44:07 +0200265 value = self._environment.undefined(
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200266 'parameter %r was not provided' % name, name=name)
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200267 arguments.append(value)
268
269 # it's important that the order of these arguments does not change
270 # if not also changed in the compiler's `function_scoping` method.
271 # the order is caller, keyword arguments, positional arguments!
Armin Ronacher71082072008-04-12 14:19:36 +0200272 if self.caller:
273 caller = kwargs.pop('caller', None)
274 if caller is None:
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200275 caller = self._environment.undefined('No caller defined',
276 name='caller')
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200277 arguments.append(caller)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200278 if self.catch_kwargs:
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200279 arguments.append(kwargs)
Armin Ronacher963f97d2008-04-25 11:44:59 +0200280 elif kwargs:
281 raise TypeError('macro %r takes no keyword argument %r' %
282 (self.name, iter(kwargs).next()))
283 if self.catch_varargs:
Armin Ronacherd84ec462008-04-29 13:43:16 +0200284 arguments.append(args[self._argument_count:])
Armin Ronacher19cf9c22008-05-01 12:49:53 +0200285 elif len(args) > self._argument_count:
286 raise TypeError('macro %r takes not more than %d argument(s)' %
287 (self.name, len(self.arguments)))
Armin Ronacher2feed1d2008-04-26 16:26:52 +0200288 return self._func(*arguments)
Armin Ronacher71082072008-04-12 14:19:36 +0200289
290 def __repr__(self):
291 return '<%s %s>' % (
292 self.__class__.__name__,
293 self.name is None and 'anonymous' or repr(self.name)
294 )
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200295
296
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200297def fail_with_undefined_error(self, *args, **kwargs):
298 """Regular callback function for undefined objects that raises an
299 `UndefinedError` on call.
300 """
301 if self._undefined_hint is None:
302 if self._undefined_obj is None:
303 hint = '%r is undefined' % self._undefined_name
304 elif not isinstance(self._undefined_name, basestring):
305 hint = '%r object has no element %r' % (
306 self._undefined_obj.__class__.__name__,
307 self._undefined_name
308 )
309 else:
310 hint = '%r object has no attribute %r' % (
311 self._undefined_obj.__class__.__name__,
312 self._undefined_name
313 )
314 else:
315 hint = self._undefined_hint
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200316 raise self._undefined_exception(hint)
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200317
318
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200319class Undefined(object):
Armin Ronacherd1342312008-04-28 12:20:12 +0200320 """The default undefined type. This undefined type can be printed and
321 iterated over, but every other access will raise an :exc:`UndefinedError`:
322
323 >>> foo = Undefined(name='foo')
324 >>> str(foo)
325 ''
326 >>> not foo
327 True
328 >>> foo + 42
329 Traceback (most recent call last):
330 ...
331 jinja2.exceptions.UndefinedError: 'foo' is undefined
Armin Ronacherc63243e2008-04-14 22:53:58 +0200332 """
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200333 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
334 '_undefined_exception')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200335
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200336 def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):
Armin Ronacher9a822052008-04-17 18:44:07 +0200337 self._undefined_hint = hint
338 self._undefined_obj = obj
339 self._undefined_name = name
Armin Ronacher5cdc1ac2008-05-07 12:17:18 +0200340 self._undefined_exception = exc
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200341
Armin Ronacherc63243e2008-04-14 22:53:58 +0200342 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
343 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \
344 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
Armin Ronacher53042292008-04-26 18:30:19 +0200345 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
346 fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200347
348 def __str__(self):
349 return self.__unicode__().encode('utf-8')
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200350
351 def __repr__(self):
Priit Laes4149a0e2008-04-17 19:04:44 +0200352 return 'Undefined'
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200353
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200354 def __unicode__(self):
355 return u''
356
Armin Ronacherd1d2f3d2008-04-09 14:02:55 +0200357 def __len__(self):
358 return 0
359
360 def __iter__(self):
361 if 0:
362 yield None
Armin Ronacherc63243e2008-04-14 22:53:58 +0200363
364 def __nonzero__(self):
365 return False
366
367
368class DebugUndefined(Undefined):
Armin Ronacherd1342312008-04-28 12:20:12 +0200369 """An undefined that returns the debug info when printed.
370
371 >>> foo = DebugUndefined(name='foo')
372 >>> str(foo)
373 '{{ foo }}'
374 >>> not foo
375 True
376 >>> foo + 42
377 Traceback (most recent call last):
378 ...
379 jinja2.exceptions.UndefinedError: 'foo' is undefined
380 """
Armin Ronacher53042292008-04-26 18:30:19 +0200381 __slots__ = ()
Armin Ronacherc63243e2008-04-14 22:53:58 +0200382
383 def __unicode__(self):
Armin Ronacher9a822052008-04-17 18:44:07 +0200384 if self._undefined_hint is None:
385 if self._undefined_obj is None:
386 return u'{{ %s }}' % self._undefined_name
387 return '{{ no such element: %s[%r] }}' % (
388 self._undefined_obj.__class__.__name__,
389 self._undefined_name
390 )
391 return u'{{ undefined value printed: %s }}' % self._undefined_hint
Armin Ronacherc63243e2008-04-14 22:53:58 +0200392
393
394class StrictUndefined(Undefined):
Armin Ronacher203bfcb2008-04-24 21:54:44 +0200395 """An undefined that barks on print and iteration as well as boolean
Armin Ronacher53042292008-04-26 18:30:19 +0200396 tests and all kinds of comparisons. In other words: you can do nothing
397 with it except checking if it's defined using the `defined` test.
Armin Ronacherd1342312008-04-28 12:20:12 +0200398
399 >>> foo = StrictUndefined(name='foo')
400 >>> str(foo)
401 Traceback (most recent call last):
402 ...
403 jinja2.exceptions.UndefinedError: 'foo' is undefined
404 >>> not foo
405 Traceback (most recent call last):
406 ...
407 jinja2.exceptions.UndefinedError: 'foo' is undefined
408 >>> foo + 42
409 Traceback (most recent call last):
410 ...
411 jinja2.exceptions.UndefinedError: 'foo' is undefined
Priit Laes4149a0e2008-04-17 19:04:44 +0200412 """
Armin Ronacher53042292008-04-26 18:30:19 +0200413 __slots__ = ()
414 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
415 fail_with_undefined_error
Armin Ronacherc63243e2008-04-14 22:53:58 +0200416
Armin Ronacher53042292008-04-26 18:30:19 +0200417
418# remove remaining slots attributes, after the metaclass did the magic they
419# are unneeded and irritating as they contain wrong data for the subclasses.
420del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__