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 # create the initial mapping of blocks. Whenever template inheritance
70 # takes place the runtime will update this mapping with the new blocks
72 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
74 def super(self, name, current):
75 """Render a parent block."""
77 blocks = self.blocks[name]
78 block = blocks[blocks.index(current) + 1]
80 return self.environment.undefined('there is no parent block '
83 wrap = self.environment.autoescape and Markup or (lambda x: x)
84 render = lambda: wrap(concat(block(self)))
85 render.__name__ = render.name = name
88 def get(self, key, default=None):
89 """Returns an item from the template context, if it doesn't exist
90 `default` is returned.
97 def resolve(self, key):
98 """Looks up a variable like `__getitem__` or `get` but returns an
99 :class:`Undefined` object with the name of the name looked up.
102 return self.vars[key]
103 if key in self.parent:
104 return self.parent[key]
105 return self.environment.undefined(name=key)
107 def get_exported(self):
108 """Get a new dict with the exported variables."""
109 return dict((k, self.vars[k]) for k in self.exported_vars)
112 """Return a copy of the complete context as dict including the
115 return dict(self.parent, **self.vars)
117 def call(__self, __obj, *args, **kwargs):
118 """Called by the template code to inject the current context
119 or environment as first arguments. Then forwards the call to
120 the object with the arguments and keyword arguments.
122 if getattr(__obj, 'contextfunction', 0):
123 args = (__self,) + args
124 elif getattr(__obj, 'environmentfunction', 0):
125 args = (__self.environment,) + args
126 return __obj(*args, **kwargs)
129 proxy = lambda self: getattr(self.get_all(), meth)()
130 proxy.__doc__ = getattr(dict, meth).__doc__
131 proxy.__name__ = meth
135 values = _all('values')
136 items = _all('items')
137 iterkeys = _all('iterkeys')
138 itervalues = _all('itervalues')
139 iteritems = _all('iteritems')
142 def __contains__(self, name):
143 return name in self.vars or name in self.parent
145 def __getitem__(self, key):
146 """Lookup a variable or raise `KeyError` if the variable is
149 item = self.resolve(key)
150 if isinstance(item, Undefined):
155 return '<%s %s of %r>' % (
156 self.__class__.__name__,
157 repr(self.get_all()),
162 class TemplateReference(object):
163 """The `self` in templates."""
165 def __init__(self, context):
166 self.__context = context
168 def __getitem__(self, name):
169 func = self.__context.blocks[name][0]
170 wrap = self.__context.environment.autoescape and \
171 Markup or (lambda x: x)
172 render = lambda: wrap(concat(func(self.__context)))
173 render.__name__ = render.name = name
178 self.__class__.__name__,
183 class LoopContext(object):
184 """A loop context for dynamic iteration."""
186 def __init__(self, iterable, enforce_length=False, recurse=None):
187 self._iterable = iterable
188 self._next = iter(iterable).next
190 self._recurse = recurse
195 def cycle(self, *args):
196 """Cycles among the arguments with the current loop index."""
198 raise TypeError('no items for cycling given')
199 return args[self.index0 % len(args)]
201 first = property(lambda x: x.index0 == 0)
202 last = property(lambda x: x.revindex0 == 0)
203 index = property(lambda x: x.index0 + 1)
204 revindex = property(lambda x: x.length - x.index0)
205 revindex0 = property(lambda x: x.length - x.index)
211 return LoopContextIterator(self)
213 def loop(self, iterable):
214 if self._recurse is None:
215 raise TypeError('Tried to call non recursive loop. Maybe you '
216 "forgot the 'recursive' modifier.")
217 return self._recurse(iterable, self._recurse)
219 # a nifty trick to enhance the error message if someone tried to call
220 # the the loop without or with too many arguments.
221 __call__ = loop; del loop
225 if self._length is None:
227 # first try to get the length from the iterable (if the
228 # iterable is a sequence)
229 length = len(self._iterable)
231 # if that's not possible (ie: iterating over a generator)
232 # we have to convert the iterable into a sequence and
233 # use the length of that.
234 self._iterable = tuple(self._iterable)
235 self._next = iter(self._iterable).next
236 length = len(tuple(self._iterable)) + self.index0 + 1
237 self._length = length
241 return '<%s %r/%r>' % (
242 self.__class__.__name__,
248 class LoopContextIterator(object):
249 """The iterator for a loop context."""
250 __slots__ = ('context',)
252 def __init__(self, context):
253 self.context = context
261 return ctx._next(), ctx
267 def __init__(self, environment, func, name, arguments, defaults,
268 catch_kwargs, catch_varargs, caller):
269 self._environment = environment
271 self._argument_count = len(arguments)
273 self.arguments = arguments
274 self.defaults = defaults
275 self.catch_kwargs = catch_kwargs
276 self.catch_varargs = catch_varargs
279 def __call__(self, *args, **kwargs):
281 for idx, name in enumerate(self.arguments):
286 value = kwargs.pop(name)
289 value = self.defaults[idx - self._argument_count]
291 value = self._environment.undefined(
292 'parameter %r was not provided' % name, name=name)
293 arguments.append(value)
295 # it's important that the order of these arguments does not change
296 # if not also changed in the compiler's `function_scoping` method.
297 # the order is caller, keyword arguments, positional arguments!
299 caller = kwargs.pop('caller', None)
301 caller = self._environment.undefined('No caller defined',
303 arguments.append(caller)
304 if self.catch_kwargs:
305 arguments.append(kwargs)
307 raise TypeError('macro %r takes no keyword argument %r' %
308 (self.name, iter(kwargs).next()))
309 if self.catch_varargs:
310 arguments.append(args[self._argument_count:])
311 elif len(args) > self._argument_count:
312 raise TypeError('macro %r takes not more than %d argument(s)' %
313 (self.name, len(self.arguments)))
314 return self._func(*arguments)
318 self.__class__.__name__,
319 self.name is None and 'anonymous' or repr(self.name)
323 def fail_with_undefined_error(self, *args, **kwargs):
324 """Regular callback function for undefined objects that raises an
325 `UndefinedError` on call.
327 if self._undefined_hint is None:
328 if self._undefined_obj is None:
329 hint = '%r is undefined' % self._undefined_name
330 elif not isinstance(self._undefined_name, basestring):
331 hint = '%r object has no element %r' % (
332 self._undefined_obj.__class__.__name__,
336 hint = '%r object has no attribute %r' % (
337 self._undefined_obj.__class__.__name__,
341 hint = self._undefined_hint
342 raise self._undefined_exception(hint)
345 class Undefined(object):
346 """The default undefined type. This undefined type can be printed and
347 iterated over, but every other access will raise an :exc:`UndefinedError`:
349 >>> foo = Undefined(name='foo')
355 Traceback (most recent call last):
357 jinja2.exceptions.UndefinedError: 'foo' is undefined
359 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
360 '_undefined_exception')
362 def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):
363 self._undefined_hint = hint
364 self._undefined_obj = obj
365 self._undefined_name = name
366 self._undefined_exception = exc
368 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
369 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \
370 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
371 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
372 fail_with_undefined_error
375 return self.__unicode__().encode('utf-8')
380 def __unicode__(self):
390 def __nonzero__(self):
394 class DebugUndefined(Undefined):
395 """An undefined that returns the debug info when printed.
397 >>> foo = DebugUndefined(name='foo')
403 Traceback (most recent call last):
405 jinja2.exceptions.UndefinedError: 'foo' is undefined
409 def __unicode__(self):
410 if self._undefined_hint is None:
411 if self._undefined_obj is None:
412 return u'{{ %s }}' % self._undefined_name
413 return '{{ no such element: %s[%r] }}' % (
414 self._undefined_obj.__class__.__name__,
417 return u'{{ undefined value printed: %s }}' % self._undefined_hint
420 class StrictUndefined(Undefined):
421 """An undefined that barks on print and iteration as well as boolean
422 tests and all kinds of comparisons. In other words: you can do nothing
423 with it except checking if it's defined using the `defined` test.
425 >>> foo = StrictUndefined(name='foo')
427 Traceback (most recent call last):
429 jinja2.exceptions.UndefinedError: 'foo' is undefined
431 Traceback (most recent call last):
433 jinja2.exceptions.UndefinedError: 'foo' is undefined
435 Traceback (most recent call last):
437 jinja2.exceptions.UndefinedError: 'foo' is undefined
440 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
441 fail_with_undefined_error
444 # remove remaining slots attributes, after the metaclass did the magic they
445 # are unneeded and irritating as they contain wrong data for the subclasses.
446 del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__