1 # -*- coding: utf-8 -*-
8 :copyright: Copyright 2008 by Armin Ronacher.
12 from types import FunctionType, MethodType
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']
23 _context_function_types = (FunctionType, MethodType)
27 """Concatenation that escapes if necessary and converts to unicode."""
29 iterator = imap(soft_unicode, seq)
32 if hasattr(arg, '__html__'):
33 return Markup(u'').join(chain(buf, iterator))
37 def unicode_join(seq):
38 """Simple args to unicode conversion and concatenation."""
39 return concat(imap(unicode, seq))
42 class Context(object):
43 """The template context holds the variables of a template. It stores the
44 values passed to the template and also the names the template exports.
45 Creating instances is neither supported nor useful as it's created
46 automatically at various stages of the template evaluation and should not
49 The context is immutable. Modifications on :attr:`parent` **must not**
50 happen and modifications on :attr:`vars` are allowed from generated
51 template code only. Template filters and global functions marked as
52 :func:`contextfunction`\s get the active context passed as first argument
53 and are allowed to access the context read-only.
55 The template context supports read only dict operations (`get`,
56 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
57 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
58 method that doesn't fail with a `KeyError` but returns an
59 :class:`Undefined` object for missing variables.
61 __slots__ = ('parent', 'vars', 'environment', 'exported_vars', 'name',
64 def __init__(self, environment, parent, name, blocks):
67 self.environment = environment
68 self.exported_vars = set()
71 # create the initial mapping of blocks. Whenever template inheritance
72 # takes place the runtime will update this mapping with the new blocks
74 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())
76 def super(self, name, current):
77 """Render a parent block."""
79 blocks = self.blocks[name]
80 block = blocks[blocks.index(current) + 1]
82 return self.environment.undefined('there is no parent block '
85 wrap = self.environment.autoescape and Markup or (lambda x: x)
86 render = lambda: wrap(concat(block(self)))
87 render.__name__ = render.name = name
90 def get(self, key, default=None):
91 """Returns an item from the template context, if it doesn't exist
92 `default` is returned.
99 def resolve(self, key):
100 """Looks up a variable like `__getitem__` or `get` but returns an
101 :class:`Undefined` object with the name of the name looked up.
104 return self.vars[key]
105 if key in self.parent:
106 return self.parent[key]
107 return self.environment.undefined(name=key)
109 def get_exported(self):
110 """Get a new dict with the exported variables."""
111 return dict((k, self.vars[k]) for k in self.exported_vars)
114 """Return a copy of the complete context as dict including the
117 return dict(self.parent, **self.vars)
119 def call(__self, __obj, *args, **kwargs):
121 __traceback_hide__ = True
122 if isinstance(__obj, _context_function_types):
123 if getattr(__obj, 'contextfunction', 0):
124 args = (__self,) + args
125 elif getattr(__obj, 'environmentfunction', 0):
126 args = (__self.environment,) + args
127 return __obj(*args, **kwargs)
130 proxy = lambda self: getattr(self.get_all(), meth)()
131 proxy.__doc__ = getattr(dict, meth).__doc__
132 proxy.__name__ = meth
136 values = _all('values')
137 items = _all('items')
138 iterkeys = _all('iterkeys')
139 itervalues = _all('itervalues')
140 iteritems = _all('iteritems')
143 def __contains__(self, name):
144 return name in self.vars or name in self.parent
146 def __getitem__(self, key):
147 """Lookup a variable or raise `KeyError` if the variable is
150 item = self.resolve(key)
151 if isinstance(item, Undefined):
156 return '<%s %s of %r>' % (
157 self.__class__.__name__,
158 repr(self.get_all()),
163 class TemplateReference(object):
164 """The `self` in templates."""
166 def __init__(self, context):
167 self.__context = context
169 def __getitem__(self, name):
170 func = self.__context.blocks[name][0]
171 wrap = self.__context.environment.autoescape and \
172 Markup or (lambda x: x)
173 render = lambda: wrap(concat(func(self.__context)))
174 render.__name__ = render.name = name
179 self.__class__.__name__,
184 class LoopContext(object):
185 """A loop context for dynamic iteration."""
187 def __init__(self, iterable, enforce_length=False, recurse=None):
188 self._iterable = iterable
189 self._next = iter(iterable).next
191 self._recurse = recurse
196 def cycle(self, *args):
197 """Cycles among the arguments with the current loop index."""
199 raise TypeError('no items for cycling given')
200 return args[self.index0 % len(args)]
202 first = property(lambda x: x.index0 == 0)
203 last = property(lambda x: x.revindex0 == 0)
204 index = property(lambda x: x.index0 + 1)
205 revindex = property(lambda x: x.length - x.index0)
206 revindex0 = property(lambda x: x.length - x.index)
212 return LoopContextIterator(self)
214 def loop(self, iterable):
215 if self._recurse is None:
216 raise TypeError('Tried to call non recursive loop. Maybe you '
217 "forgot the 'recursive' modifier.")
218 return self._recurse(iterable, self._recurse)
220 # a nifty trick to enhance the error message if someone tried to call
221 # the the loop without or with too many arguments.
222 __call__ = loop; del loop
226 if self._length is None:
228 # first try to get the length from the iterable (if the
229 # iterable is a sequence)
230 length = len(self._iterable)
232 # if that's not possible (ie: iterating over a generator)
233 # we have to convert the iterable into a sequence and
234 # use the length of that.
235 self._iterable = tuple(self._iterable)
236 self._next = iter(self._iterable).next
237 length = len(tuple(self._iterable)) + self.index0 + 1
238 self._length = length
242 return '<%s %r/%r>' % (
243 self.__class__.__name__,
249 class LoopContextIterator(object):
250 """The iterator for a loop context."""
251 __slots__ = ('context',)
253 def __init__(self, context):
254 self.context = context
262 return ctx._next(), ctx
268 def __init__(self, environment, func, name, arguments, defaults,
269 catch_kwargs, catch_varargs, caller):
270 self._environment = environment
272 self._argument_count = len(arguments)
274 self.arguments = arguments
275 self.defaults = defaults
276 self.catch_kwargs = catch_kwargs
277 self.catch_varargs = catch_varargs
280 def __call__(self, *args, **kwargs):
282 for idx, name in enumerate(self.arguments):
287 value = kwargs.pop(name)
290 value = self.defaults[idx - self._argument_count]
292 value = self._environment.undefined(
293 'parameter %r was not provided' % name, name=name)
294 arguments.append(value)
296 # it's important that the order of these arguments does not change
297 # if not also changed in the compiler's `function_scoping` method.
298 # the order is caller, keyword arguments, positional arguments!
300 caller = kwargs.pop('caller', None)
302 caller = self._environment.undefined('No caller defined',
304 arguments.append(caller)
305 if self.catch_kwargs:
306 arguments.append(kwargs)
308 raise TypeError('macro %r takes no keyword argument %r' %
309 (self.name, iter(kwargs).next()))
310 if self.catch_varargs:
311 arguments.append(args[self._argument_count:])
312 elif len(args) > self._argument_count:
313 raise TypeError('macro %r takes not more than %d argument(s)' %
314 (self.name, len(self.arguments)))
315 return self._func(*arguments)
319 self.__class__.__name__,
320 self.name is None and 'anonymous' or repr(self.name)
324 def fail_with_undefined_error(self, *args, **kwargs):
325 """Regular callback function for undefined objects that raises an
326 `UndefinedError` on call.
328 if self._undefined_hint is None:
329 if self._undefined_obj is None:
330 hint = '%r is undefined' % self._undefined_name
331 elif not isinstance(self._undefined_name, basestring):
332 hint = '%r object has no element %r' % (
333 self._undefined_obj.__class__.__name__,
337 hint = '%r object has no attribute %r' % (
338 self._undefined_obj.__class__.__name__,
342 hint = self._undefined_hint
343 raise self._undefined_exception(hint)
346 class Undefined(object):
347 """The default undefined type. This undefined type can be printed and
348 iterated over, but every other access will raise an :exc:`UndefinedError`:
350 >>> foo = Undefined(name='foo')
356 Traceback (most recent call last):
358 jinja2.exceptions.UndefinedError: 'foo' is undefined
360 __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
361 '_undefined_exception')
363 def __init__(self, hint=None, obj=None, name=None, exc=UndefinedError):
364 self._undefined_hint = hint
365 self._undefined_obj = obj
366 self._undefined_name = name
367 self._undefined_exception = exc
369 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
370 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \
371 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
372 __getattr__ = __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = \
373 fail_with_undefined_error
376 return self.__unicode__().encode('utf-8')
381 def __unicode__(self):
391 def __nonzero__(self):
395 class DebugUndefined(Undefined):
396 """An undefined that returns the debug info when printed.
398 >>> foo = DebugUndefined(name='foo')
404 Traceback (most recent call last):
406 jinja2.exceptions.UndefinedError: 'foo' is undefined
410 def __unicode__(self):
411 if self._undefined_hint is None:
412 if self._undefined_obj is None:
413 return u'{{ %s }}' % self._undefined_name
414 return '{{ no such element: %s[%r] }}' % (
415 self._undefined_obj.__class__.__name__,
418 return u'{{ undefined value printed: %s }}' % self._undefined_hint
421 class StrictUndefined(Undefined):
422 """An undefined that barks on print and iteration as well as boolean
423 tests and all kinds of comparisons. In other words: you can do nothing
424 with it except checking if it's defined using the `defined` test.
426 >>> foo = StrictUndefined(name='foo')
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
436 Traceback (most recent call last):
438 jinja2.exceptions.UndefinedError: 'foo' is undefined
441 __iter__ = __unicode__ = __len__ = __nonzero__ = __eq__ = __ne__ = \
442 fail_with_undefined_error
445 # remove remaining slots attributes, after the metaclass did the magic they
446 # are unneeded and irritating as they contain wrong data for the subclasses.
447 del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__