1 # -*- coding: utf-8 -*-
8 :copyright: Copyright 2008 by Armin Ronacher.
12 from types import FunctionType
13 from itertools import chain, imap
14 from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat
15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError
18 # these variables are exported to the template runtime
19 __all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',
20 'TemplateRuntimeError', 'missing', 'concat', 'escape',
21 'markup_join', 'unicode_join']
25 """Concatenation that escapes if necessary and converts to unicode."""
27 iterator = imap(soft_unicode, seq)
30 if hasattr(arg, '__html__'):
31 return Markup(u'').join(chain(buf, iterator))
35 def unicode_join(seq):
36 """Simple args to unicode conversion and concatenation."""
37 return concat(imap(unicode, seq))
40 class Context(object):
41 """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
47 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.
53 The template context supports read only dict operations (`get`,
54 `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.
59 __slots__ = ('parent', 'vars', 'environment', 'exported_vars', 'name',
62 def __init__(self, environment, parent, name, blocks):
65 self.environment = environment
66 self.exported_vars = set()
69 # bind functions to the context of environment if required
70 for name, obj in parent.iteritems():
71 if type(obj) is FunctionType:
72 if getattr(obj, 'contextfunction', 0):
73 vars[name] = partial(obj, self)
74 elif getattr(obj, 'environmentfunction', 0):
75 vars[name] = partial(obj, environment)
77 # create the initial mapping of blocks. Whenever template inheritance
78 # takes place the runtime will update this mapping with the new blocks
80 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
82 def super(self, name, current):
83 """Render a parent block."""
85 blocks = self.blocks[name]
86 block = blocks[blocks.index(current) + 1]
88 return self.environment.undefined('there is no parent block '
91 wrap = self.environment.autoescape and Markup or (lambda x: x)
92 render = lambda: wrap(concat(block(self)))
93 render.__name__ = render.name = name
96 def get(self, key, default=None):
97 """Returns an item from the template context, if it doesn't exist
98 `default` is returned.
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.
110 return self.vars[key]
111 if key in self.parent:
112 return self.parent[key]
113 return self.environment.undefined(name=key)
115 def get_exported(self):
116 """Get a new dict with the exported variables."""
117 return dict((k, self.vars[k]) for k in self.exported_vars)
120 """Return a copy of the complete context as dict including the
123 return dict(self.parent, **self.vars)
126 proxy = lambda self: getattr(self.get_all(), meth)()
127 proxy.__doc__ = getattr(dict, meth).__doc__
128 proxy.__name__ = meth
132 values = _all('values')
133 items = _all('items')
134 iterkeys = _all('iterkeys')
135 itervalues = _all('itervalues')
136 iteritems = _all('iteritems')
139 def __contains__(self, name):
140 return name in self.vars or name in self.parent
142 def __getitem__(self, key):
143 """Lookup a variable or raise `KeyError` if the variable is
146 item = self.resolve(key)
147 if isinstance(item, Undefined):
152 return '<%s %s of %r>' % (
153 self.__class__.__name__,
154 repr(self.get_all()),
159 class TemplateReference(object):
160 """The `self` in templates."""
162 def __init__(self, context):
163 self.__context = context
165 def __getitem__(self, name):
166 func = self.__context.blocks[name][-1]
167 wrap = self.__context.environment.autoescape and \
168 Markup or (lambda x: x)
169 render = lambda: wrap(concat(func(self.__context)))
170 render.__name__ = render.name = name
175 self.__class__.__name__,
180 class LoopContext(object):
181 """A loop context for dynamic iteration."""
183 def __init__(self, iterable, enforce_length=False, recurse=None):
184 self._iterable = iterable
185 self._next = iter(iterable).next
187 self._recurse = recurse
192 def cycle(self, *args):
193 """Cycles among the arguments with the current loop index."""
195 raise TypeError('no items for cycling given')
196 return args[self.index0 % len(args)]
198 first = property(lambda x: x.index0 == 0)
199 last = property(lambda x: x.revindex0 == 0)
200 index = property(lambda x: x.index0 + 1)
201 revindex = property(lambda x: x.length - x.index0)
202 revindex0 = property(lambda x: x.length - x.index)
208 return LoopContextIterator(self)
210 def loop(self, iterable):
211 if self._recurse is None:
212 raise TypeError('Tried to call non recursive loop. Maybe you '
213 "forgot the 'recursive' modifier.")
214 return self._recurse(iterable, self._recurse)
216 # a nifty trick to enhance the error message if someone tried to call
217 # the the loop without or with too many arguments.
218 __call__ = loop; del loop
222 if self._length is None:
224 # first try to get the length from the iterable (if the
225 # iterable is a sequence)
226 length = len(self._iterable)
228 # if that's not possible (ie: iterating over a generator)
229 # we have to convert the iterable into a sequence and
230 # use the length of that.
231 self._iterable = tuple(self._iterable)
232 self._next = iter(self._iterable).next
233 length = len(tuple(self._iterable)) + self.index0 + 1
234 self._length = length
238 return '<%s %r/%r>' % (
239 self.__class__.__name__,
245 class LoopContextIterator(object):
246 """The iterator for a loop context."""
247 __slots__ = ('context',)
249 def __init__(self, context):
250 self.context = context
258 return ctx._next(), ctx
264 def __init__(self, environment, func, name, arguments, defaults,
265 catch_kwargs, catch_varargs, caller):
266 self._environment = environment
268 self._argument_count = len(arguments)
270 self.arguments = arguments
271 self.defaults = defaults
272 self.catch_kwargs = catch_kwargs
273 self.catch_varargs = catch_varargs
276 def __call__(self, *args, **kwargs):
278 for idx, name in enumerate(self.arguments):
283 value = kwargs.pop(name)
286 value = self.defaults[idx - self._argument_count]
288 value = self._environment.undefined(
289 'parameter %r was not provided' % name, name=name)
290 arguments.append(value)
292 # it's important that the order of these arguments does not change
293 # if not also changed in the compiler's `function_scoping` method.
294 # the order is caller, keyword arguments, positional arguments!
296 caller = kwargs.pop('caller', None)
298 caller = self._environment.undefined('No caller defined',
300 arguments.append(caller)
301 if self.catch_kwargs:
302 arguments.append(kwargs)
304 raise TypeError('macro %r takes no keyword argument %r' %
305 (self.name, iter(kwargs).next()))
306 if self.catch_varargs:
307 arguments.append(args[self._argument_count:])
308 elif len(args) > self._argument_count:
309 raise TypeError('macro %r takes not more than %d argument(s)' %
310 (self.name, len(self.arguments)))
311 return self._func(*arguments)
315 self.__class__.__name__,
316 self.name is None and 'anonymous' or repr(self.name)
320 def fail_with_undefined_error(self, *args, **kwargs):
321 """Regular callback function for undefined objects that raises an
322 `UndefinedError` on call.
324 if self._undefined_hint is None:
325 if self._undefined_obj is None:
326 hint = '%r is undefined' % self._undefined_name
327 elif not isinstance(self._undefined_name, basestring):
328 hint = '%r object has no element %r' % (
329 self._undefined_obj.__class__.__name__,
333 hint = '%r object has no attribute %r' % (
334 self._undefined_obj.__class__.__name__,
338 hint = self._undefined_hint
339 raise self._undefined_exception(hint)
342 class Undefined(object):
343 """The default undefined type. This undefined type can be printed and
344 iterated over, but every other access will raise an :exc:`UndefinedError`:
346 >>> foo = Undefined(name='foo')
352 Traceback (most recent call last):
354 jinja2.exceptions.UndefinedError: 'foo' is undefined
356 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
357 '_undefined_exception')
359 def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):
360 self._undefined_hint = hint
361 self._undefined_obj = obj
362 self._undefined_name = name
363 self._undefined_exception = exc
365 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
366 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \
367 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
368 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
369 fail_with_undefined_error
372 return self.__unicode__().encode('utf-8')
377 def __unicode__(self):
387 def __nonzero__(self):
391 class DebugUndefined(Undefined):
392 """An undefined that returns the debug info when printed.
394 >>> foo = DebugUndefined(name='foo')
400 Traceback (most recent call last):
402 jinja2.exceptions.UndefinedError: 'foo' is undefined
406 def __unicode__(self):
407 if self._undefined_hint is None:
408 if self._undefined_obj is None:
409 return u'{{ %s }}' % self._undefined_name
410 return '{{ no such element: %s[%r] }}' % (
411 self._undefined_obj.__class__.__name__,
414 return u'{{ undefined value printed: %s }}' % self._undefined_hint
417 class StrictUndefined(Undefined):
418 """An undefined that barks on print and iteration as well as boolean
419 tests and all kinds of comparisons. In other words: you can do nothing
420 with it except checking if it's defined using the `defined` test.
422 >>> foo = StrictUndefined(name='foo')
424 Traceback (most recent call last):
426 jinja2.exceptions.UndefinedError: 'foo' is undefined
428 Traceback (most recent call last):
430 jinja2.exceptions.UndefinedError: 'foo' is undefined
432 Traceback (most recent call last):
434 jinja2.exceptions.UndefinedError: 'foo' is undefined
437 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
438 fail_with_undefined_error
441 # remove remaining slots attributes, after the metaclass did the magic they
442 # are unneeded and irritating as they contain wrong data for the subclasses.
443 del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__