2008-04-07 16:39:54 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
"""
|
|
|
|
jinja2.runtime
|
|
|
|
~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Runtime helpers.
|
|
|
|
|
2017-01-07 15:17:14 +00:00
|
|
|
:copyright: (c) 2017 by the Jinja Team.
|
2008-07-14 22:11:14 +00:00
|
|
|
:license: BSD.
|
2008-04-07 16:39:54 +00:00
|
|
|
"""
|
2014-06-06 16:00:04 +00:00
|
|
|
import sys
|
|
|
|
|
2013-05-17 22:06:22 +00:00
|
|
|
from itertools import chain
|
2017-03-15 18:19:04 +00:00
|
|
|
from types import MethodType
|
|
|
|
|
2010-05-23 20:58:28 +00:00
|
|
|
from jinja2.nodes import EvalContext, _context_function_types
|
2013-05-18 10:52:40 +00:00
|
|
|
from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \
|
2017-02-26 15:45:54 +00:00
|
|
|
internalcode, object_type_repr, evalcontextfunction, Namespace
|
2008-12-27 12:10:38 +00:00
|
|
|
from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \
|
|
|
|
TemplateNotFound
|
2013-05-20 15:54:48 +00:00
|
|
|
from jinja2._compat import imap, text_type, iteritems, \
|
2017-01-12 19:10:58 +00:00
|
|
|
implements_iterator, implements_to_string, string_types, PY2, \
|
2018-06-27 13:30:54 +00:00
|
|
|
with_metaclass, abc
|
2008-04-07 16:39:54 +00:00
|
|
|
|
|
|
|
|
2008-04-26 14:26:52 +00:00
|
|
|
# these variables are exported to the template runtime
|
2009-02-19 14:56:53 +00:00
|
|
|
__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
|
2008-05-01 10:49:53 +00:00
|
|
|
'TemplateRuntimeError', 'missing', 'concat', 'escape',
|
2010-05-29 15:35:10 +00:00
|
|
|
'markup_join', 'unicode_join', 'to_string', 'identity',
|
2017-02-26 15:45:54 +00:00
|
|
|
'TemplateNotFound', 'Namespace']
|
2008-04-25 21:44:14 +00:00
|
|
|
|
2009-08-05 18:25:06 +00:00
|
|
|
#: the name of the function that is used to convert something into
|
2013-05-20 00:51:26 +00:00
|
|
|
#: a string. We can just use the text type here.
|
|
|
|
to_string = text_type
|
2009-08-05 18:25:06 +00:00
|
|
|
|
2010-05-29 15:35:10 +00:00
|
|
|
#: the identity function. Useful for certain things in the environment
|
|
|
|
identity = lambda x: x
|
|
|
|
|
2017-02-01 20:05:03 +00:00
|
|
|
_first_iteration = object()
|
2012-01-24 23:42:54 +00:00
|
|
|
_last_iteration = object()
|
|
|
|
|
2008-04-25 21:44:14 +00:00
|
|
|
|
2008-05-15 20:47:27 +00:00
|
|
|
def markup_join(seq):
|
2008-04-28 10:20:12 +00:00
|
|
|
"""Concatenation that escapes if necessary and converts to unicode."""
|
|
|
|
buf = []
|
2013-05-19 13:16:13 +00:00
|
|
|
iterator = imap(soft_unicode, seq)
|
2008-04-28 10:20:12 +00:00
|
|
|
for arg in iterator:
|
|
|
|
buf.append(arg)
|
|
|
|
if hasattr(arg, '__html__'):
|
|
|
|
return Markup(u'').join(chain(buf, iterator))
|
|
|
|
return concat(buf)
|
|
|
|
|
|
|
|
|
2008-05-15 20:47:27 +00:00
|
|
|
def unicode_join(seq):
|
2008-04-28 10:20:12 +00:00
|
|
|
"""Simple args to unicode conversion and concatenation."""
|
2013-05-19 13:16:13 +00:00
|
|
|
return concat(imap(text_type, seq))
|
2008-04-28 10:20:12 +00:00
|
|
|
|
|
|
|
|
2009-02-19 14:56:53 +00:00
|
|
|
def new_context(environment, template_name, blocks, vars=None,
|
|
|
|
shared=None, globals=None, locals=None):
|
|
|
|
"""Internal helper to for context creation."""
|
|
|
|
if vars is None:
|
|
|
|
vars = {}
|
|
|
|
if shared:
|
|
|
|
parent = vars
|
|
|
|
else:
|
|
|
|
parent = dict(globals or (), **vars)
|
|
|
|
if locals:
|
|
|
|
# if the parent is shared a copy should be created because
|
|
|
|
# we don't want to modify the dict passed
|
|
|
|
if shared:
|
|
|
|
parent = dict(parent)
|
2017-01-06 19:57:30 +00:00
|
|
|
for key, value in iteritems(locals):
|
|
|
|
if value is not missing:
|
|
|
|
parent[key] = value
|
2015-04-06 12:08:46 +00:00
|
|
|
return environment.context_class(environment, parent, template_name,
|
|
|
|
blocks)
|
2009-02-19 14:56:53 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TemplateReference(object):
|
|
|
|
"""The `self` in templates."""
|
|
|
|
|
|
|
|
def __init__(self, context):
|
|
|
|
self.__context = context
|
|
|
|
|
|
|
|
def __getitem__(self, name):
|
|
|
|
blocks = self.__context.blocks[name]
|
|
|
|
return BlockReference(name, self.__context, blocks, 0)
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '<%s %r>' % (
|
|
|
|
self.__class__.__name__,
|
|
|
|
self.__context.name
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2017-01-12 19:10:58 +00:00
|
|
|
def _get_func(x):
|
|
|
|
return getattr(x, '__func__', x)
|
|
|
|
|
|
|
|
|
|
|
|
class ContextMeta(type):
|
|
|
|
|
|
|
|
def __new__(cls, name, bases, d):
|
|
|
|
rv = type.__new__(cls, name, bases, d)
|
|
|
|
if bases == ():
|
|
|
|
return rv
|
|
|
|
|
|
|
|
resolve = _get_func(rv.resolve)
|
|
|
|
default_resolve = _get_func(Context.resolve)
|
|
|
|
resolve_or_missing = _get_func(rv.resolve_or_missing)
|
|
|
|
default_resolve_or_missing = _get_func(Context.resolve_or_missing)
|
|
|
|
|
|
|
|
# If we have a changed resolve but no changed default or missing
|
|
|
|
# resolve we invert the call logic.
|
|
|
|
if resolve is not default_resolve and \
|
|
|
|
resolve_or_missing is default_resolve_or_missing:
|
|
|
|
rv._legacy_resolve_mode = True
|
|
|
|
elif resolve is default_resolve and \
|
|
|
|
resolve_or_missing is default_resolve_or_missing:
|
|
|
|
rv._fast_resolve_mode = True
|
|
|
|
|
|
|
|
return rv
|
|
|
|
|
|
|
|
|
|
|
|
def resolve_or_missing(context, key, missing=missing):
|
|
|
|
if key in context.vars:
|
|
|
|
return context.vars[key]
|
|
|
|
if key in context.parent:
|
|
|
|
return context.parent[key]
|
|
|
|
return missing
|
|
|
|
|
|
|
|
|
|
|
|
class Context(with_metaclass(ContextMeta)):
|
2008-04-30 11:03:59 +00:00
|
|
|
"""The template context holds the variables of a template. It stores the
|
|
|
|
values passed to the template and also the names the template exports.
|
|
|
|
Creating instances is neither supported nor useful as it's created
|
|
|
|
automatically at various stages of the template evaluation and should not
|
|
|
|
be created by hand.
|
|
|
|
|
|
|
|
The context is immutable. Modifications on :attr:`parent` **must not**
|
|
|
|
happen and modifications on :attr:`vars` are allowed from generated
|
|
|
|
template code only. Template filters and global functions marked as
|
2017-01-08 22:40:38 +00:00
|
|
|
:func:`contextfunction`\\s get the active context passed as first argument
|
2008-04-30 11:03:59 +00:00
|
|
|
and are allowed to access the context read-only.
|
|
|
|
|
|
|
|
The template context supports read only dict operations (`get`,
|
2008-05-06 14:04:10 +00:00
|
|
|
`keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
|
|
|
|
`__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
|
|
|
|
method that doesn't fail with a `KeyError` but returns an
|
|
|
|
:class:`Undefined` object for missing variables.
|
2008-04-08 16:49:56 +00:00
|
|
|
"""
|
2017-01-12 19:10:58 +00:00
|
|
|
# XXX: we want to eventually make this be a deprecation warning and
|
|
|
|
# remove it.
|
|
|
|
_legacy_resolve_mode = False
|
|
|
|
_fast_resolve_mode = False
|
2008-04-07 16:39:54 +00:00
|
|
|
|
2008-04-24 19:54:44 +00:00
|
|
|
def __init__(self, environment, parent, name, blocks):
|
|
|
|
self.parent = parent
|
2009-10-26 10:53:27 +00:00
|
|
|
self.vars = {}
|
2008-04-14 20:53:58 +00:00
|
|
|
self.environment = environment
|
2010-04-05 16:11:18 +00:00
|
|
|
self.eval_ctx = EvalContext(self.environment, name)
|
2008-04-24 19:54:44 +00:00
|
|
|
self.exported_vars = set()
|
2008-04-17 09:50:39 +00:00
|
|
|
self.name = name
|
2008-04-24 19:54:44 +00:00
|
|
|
|
|
|
|
# create the initial mapping of blocks. Whenever template inheritance
|
|
|
|
# takes place the runtime will update this mapping with the new blocks
|
|
|
|
# from the template.
|
2013-05-19 13:16:13 +00:00
|
|
|
self.blocks = dict((k, [v]) for k, v in iteritems(blocks))
|
2008-04-11 20:21:00 +00:00
|
|
|
|
2017-01-12 19:10:58 +00:00
|
|
|
# In case we detect the fast resolve mode we can set up an alias
|
|
|
|
# here that bypasses the legacy code logic.
|
|
|
|
if self._fast_resolve_mode:
|
2017-03-15 18:19:04 +00:00
|
|
|
self.resolve_or_missing = MethodType(resolve_or_missing, self)
|
2017-01-12 19:10:58 +00:00
|
|
|
|
2008-04-24 19:54:44 +00:00
|
|
|
def super(self, name, current):
|
2008-04-13 21:18:05 +00:00
|
|
|
"""Render a parent block."""
|
2008-04-27 19:28:03 +00:00
|
|
|
try:
|
|
|
|
blocks = self.blocks[name]
|
2008-09-20 10:04:53 +00:00
|
|
|
index = blocks.index(current) + 1
|
|
|
|
blocks[index]
|
2008-04-27 19:28:03 +00:00
|
|
|
except LookupError:
|
2008-04-17 16:44:07 +00:00
|
|
|
return self.environment.undefined('there is no parent block '
|
2008-05-01 10:49:53 +00:00
|
|
|
'called %r.' % name,
|
|
|
|
name='super')
|
2008-09-20 10:04:53 +00:00
|
|
|
return BlockReference(name, self, blocks, index)
|
2008-04-07 16:39:54 +00:00
|
|
|
|
2008-04-26 16:30:19 +00:00
|
|
|
def get(self, key, default=None):
|
2008-04-30 11:03:59 +00:00
|
|
|
"""Returns an item from the template context, if it doesn't exist
|
|
|
|
`default` is returned.
|
|
|
|
"""
|
2008-05-06 14:04:10 +00:00
|
|
|
try:
|
|
|
|
return self[key]
|
|
|
|
except KeyError:
|
|
|
|
return default
|
|
|
|
|
|
|
|
def resolve(self, key):
|
|
|
|
"""Looks up a variable like `__getitem__` or `get` but returns an
|
|
|
|
:class:`Undefined` object with the name of the name looked up.
|
|
|
|
"""
|
2017-01-12 19:10:58 +00:00
|
|
|
if self._legacy_resolve_mode:
|
|
|
|
rv = resolve_or_missing(self, key)
|
|
|
|
else:
|
|
|
|
rv = self.resolve_or_missing(key)
|
2017-01-02 11:09:52 +00:00
|
|
|
if rv is missing:
|
|
|
|
return self.environment.undefined(name=key)
|
|
|
|
return rv
|
|
|
|
|
|
|
|
def resolve_or_missing(self, key):
|
|
|
|
"""Resolves a variable like :meth:`resolve` but returns the
|
|
|
|
special `missing` value if it cannot be found.
|
|
|
|
"""
|
2017-01-12 19:10:58 +00:00
|
|
|
if self._legacy_resolve_mode:
|
|
|
|
rv = self.resolve(key)
|
|
|
|
if isinstance(rv, Undefined):
|
|
|
|
rv = missing
|
|
|
|
return rv
|
|
|
|
return resolve_or_missing(self, key)
|
2008-04-24 22:36:14 +00:00
|
|
|
|
2008-04-08 16:49:56 +00:00
|
|
|
def get_exported(self):
|
2008-04-24 19:54:44 +00:00
|
|
|
"""Get a new dict with the exported variables."""
|
2008-04-27 19:28:03 +00:00
|
|
|
return dict((k, self.vars[k]) for k in self.exported_vars)
|
2008-04-24 19:54:44 +00:00
|
|
|
|
|
|
|
def get_all(self):
|
2017-01-07 14:35:21 +00:00
|
|
|
"""Return the complete context as dict including the exported
|
|
|
|
variables. For optimizations reasons this might not return an
|
|
|
|
actual copy so be careful with using it.
|
2008-04-30 11:03:59 +00:00
|
|
|
"""
|
2017-01-07 14:35:21 +00:00
|
|
|
if not self.vars:
|
|
|
|
return self.parent
|
|
|
|
if not self.parent:
|
|
|
|
return self.vars
|
2008-04-24 19:54:44 +00:00
|
|
|
return dict(self.parent, **self.vars)
|
|
|
|
|
2009-02-24 21:58:00 +00:00
|
|
|
@internalcode
|
2008-05-24 22:16:51 +00:00
|
|
|
def call(__self, __obj, *args, **kwargs):
|
2008-05-28 09:26:59 +00:00
|
|
|
"""Call the callable with the arguments and keyword arguments
|
|
|
|
provided but inject the active context or environment as first
|
|
|
|
argument if the callable is a :func:`contextfunction` or
|
|
|
|
:func:`environmentfunction`.
|
|
|
|
"""
|
2008-05-26 11:35:58 +00:00
|
|
|
if __debug__:
|
2014-06-06 16:00:04 +00:00
|
|
|
__traceback_hide__ = True # noqa
|
2013-05-18 10:58:12 +00:00
|
|
|
|
2013-04-16 05:49:02 +00:00
|
|
|
# Allow callable classes to take a context
|
runtime: avoid assumption that all objects provide __call__
Objects which are backed by native extensions do not provide
a __call__ attribute, but are none the less callable if the
native extension provides a 'tp_call' implementation.
The jinja2.runtime.Context.call method unconditionally
access the '__call__' attribute causing an exception to be
raised if the object was a native extension method.
A demo of the problem can be seen using PyGObject:
$ cat demo.py
#!/usr/bin/python
from gi.repository import Gio
from jinja2 import Environment
f = Gio.File.new_for_path("/some/file.txt")
print f.get_uri()
t = Environment().from_string("""{{f.get_uri()}}""")
print t.render(f=f)
Which when run results in
$ ./demo.py
file:///some/file.txt
Traceback (most recent call last):
File "./demo.py", line 10, in <module>
print t.render(f=f)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 969, in render
return self.environment.handle_exception(exc_info, True)
File "/usr/lib/python2.7/site-packages/jinja2/environment.py", line 742, in handle_exception
reraise(exc_type, exc_value, tb)
File "<template>", line 1, in top-level template code
AttributeError: 'gi.FunctionInfo' object has no attribute '__call__'
After this patch it produces
$ ./demo.py
file:///some/file.txt
file:///some/file.txt
Signed-off-by: Daniel P. Berrange <berrange@redhat.com>
2015-10-13 15:52:07 +00:00
|
|
|
if hasattr(__obj, '__call__'):
|
|
|
|
fn = __obj.__call__
|
|
|
|
for fn_type in ('contextfunction',
|
|
|
|
'evalcontextfunction',
|
|
|
|
'environmentfunction'):
|
|
|
|
if hasattr(fn, fn_type):
|
|
|
|
__obj = fn
|
|
|
|
break
|
2013-05-18 10:58:12 +00:00
|
|
|
|
2008-05-26 11:35:58 +00:00
|
|
|
if isinstance(__obj, _context_function_types):
|
|
|
|
if getattr(__obj, 'contextfunction', 0):
|
|
|
|
args = (__self,) + args
|
2010-03-14 18:43:47 +00:00
|
|
|
elif getattr(__obj, 'evalcontextfunction', 0):
|
|
|
|
args = (__self.eval_ctx,) + args
|
2008-05-26 11:35:58 +00:00
|
|
|
elif getattr(__obj, 'environmentfunction', 0):
|
|
|
|
args = (__self.environment,) + args
|
2010-06-05 12:32:06 +00:00
|
|
|
try:
|
|
|
|
return __obj(*args, **kwargs)
|
|
|
|
except StopIteration:
|
|
|
|
return __self.environment.undefined('value was undefined because '
|
|
|
|
'a callable raised a '
|
|
|
|
'StopIteration exception')
|
2008-05-24 22:16:51 +00:00
|
|
|
|
2009-02-19 14:56:53 +00:00
|
|
|
def derived(self, locals=None):
|
2017-01-08 10:21:32 +00:00
|
|
|
"""Internal helper function to create a derived context. This is
|
|
|
|
used in situations where the system needs a new context in the same
|
|
|
|
template that is independent.
|
|
|
|
"""
|
2009-02-19 15:11:11 +00:00
|
|
|
context = new_context(self.environment, self.name, {},
|
2017-01-08 10:21:32 +00:00
|
|
|
self.get_all(), True, None, locals)
|
2010-03-14 18:43:47 +00:00
|
|
|
context.eval_ctx = self.eval_ctx
|
2013-05-19 13:16:13 +00:00
|
|
|
context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))
|
2009-02-19 15:11:11 +00:00
|
|
|
return context
|
2009-02-19 14:56:53 +00:00
|
|
|
|
2008-05-06 14:04:10 +00:00
|
|
|
def _all(meth):
|
2008-05-15 14:22:07 +00:00
|
|
|
proxy = lambda self: getattr(self.get_all(), meth)()
|
2008-05-06 14:04:10 +00:00
|
|
|
proxy.__doc__ = getattr(dict, meth).__doc__
|
|
|
|
proxy.__name__ = meth
|
|
|
|
return proxy
|
|
|
|
|
|
|
|
keys = _all('keys')
|
|
|
|
values = _all('values')
|
|
|
|
items = _all('items')
|
2009-08-05 16:45:39 +00:00
|
|
|
|
|
|
|
# not available on python 3
|
2013-05-20 01:15:04 +00:00
|
|
|
if PY2:
|
2009-08-05 16:45:39 +00:00
|
|
|
iterkeys = _all('iterkeys')
|
|
|
|
itervalues = _all('itervalues')
|
|
|
|
iteritems = _all('iteritems')
|
2008-05-06 14:04:10 +00:00
|
|
|
del _all
|
|
|
|
|
2008-04-24 22:36:14 +00:00
|
|
|
def __contains__(self, name):
|
|
|
|
return name in self.vars or name in self.parent
|
|
|
|
|
2008-04-24 19:54:44 +00:00
|
|
|
def __getitem__(self, key):
|
2008-05-18 22:23:37 +00:00
|
|
|
"""Lookup a variable or raise `KeyError` if the variable is
|
|
|
|
undefined.
|
|
|
|
"""
|
2017-01-02 11:09:52 +00:00
|
|
|
item = self.resolve_or_missing(key)
|
|
|
|
if item is missing:
|
2008-05-18 22:23:37 +00:00
|
|
|
raise KeyError(key)
|
|
|
|
return item
|
2008-04-08 16:09:13 +00:00
|
|
|
|
2008-04-11 20:21:00 +00:00
|
|
|
def __repr__(self):
|
|
|
|
return '<%s %s of %r>' % (
|
|
|
|
self.__class__.__name__,
|
2008-04-25 09:44:59 +00:00
|
|
|
repr(self.get_all()),
|
2008-04-17 09:50:39 +00:00
|
|
|
self.name
|
2008-04-11 20:21:00 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
2018-06-27 13:30:54 +00:00
|
|
|
abc.Mapping.register(Context)
|
2008-05-28 09:26:59 +00:00
|
|
|
|
|
|
|
|
2008-09-20 10:04:53 +00:00
|
|
|
class BlockReference(object):
|
|
|
|
"""One block on a template reference."""
|
|
|
|
|
|
|
|
def __init__(self, name, context, stack, depth):
|
|
|
|
self.name = name
|
|
|
|
self._context = context
|
|
|
|
self._stack = stack
|
|
|
|
self._depth = depth
|
|
|
|
|
|
|
|
@property
|
|
|
|
def super(self):
|
|
|
|
"""Super the block."""
|
|
|
|
if self._depth + 1 >= len(self._stack):
|
|
|
|
return self._context.environment. \
|
|
|
|
undefined('there is no parent block called %r.' %
|
|
|
|
self.name, name='super')
|
|
|
|
return BlockReference(self.name, self._context, self._stack,
|
|
|
|
self._depth + 1)
|
|
|
|
|
2009-02-24 21:58:00 +00:00
|
|
|
@internalcode
|
2008-09-20 10:04:53 +00:00
|
|
|
def __call__(self):
|
|
|
|
rv = concat(self._stack[self._depth](self._context))
|
2010-04-05 16:11:18 +00:00
|
|
|
if self._context.eval_ctx.autoescape:
|
2008-09-20 10:04:53 +00:00
|
|
|
rv = Markup(rv)
|
|
|
|
return rv
|
|
|
|
|
|
|
|
|
2016-12-28 19:06:34 +00:00
|
|
|
class LoopContextBase(object):
|
2008-04-26 21:21:03 +00:00
|
|
|
"""A loop context for dynamic iteration."""
|
2008-04-09 10:14:24 +00:00
|
|
|
|
2017-02-01 20:05:03 +00:00
|
|
|
_before = _first_iteration
|
|
|
|
_current = _first_iteration
|
2016-12-28 19:06:34 +00:00
|
|
|
_after = _last_iteration
|
|
|
|
_length = None
|
|
|
|
|
2017-02-01 20:05:03 +00:00
|
|
|
def __init__(self, undefined, recurse=None, depth0=0):
|
|
|
|
self._undefined = undefined
|
2008-05-11 21:21:16 +00:00
|
|
|
self._recurse = recurse
|
2008-04-26 21:21:03 +00:00
|
|
|
self.index0 = -1
|
2013-05-20 08:26:57 +00:00
|
|
|
self.depth0 = depth0
|
2017-02-01 20:47:17 +00:00
|
|
|
self._last_checked_value = missing
|
2008-07-04 14:35:10 +00:00
|
|
|
|
2008-04-16 12:21:57 +00:00
|
|
|
def cycle(self, *args):
|
2008-05-18 18:25:28 +00:00
|
|
|
"""Cycles among the arguments with the current loop index."""
|
2008-04-16 12:21:57 +00:00
|
|
|
if not args:
|
|
|
|
raise TypeError('no items for cycling given')
|
|
|
|
return args[self.index0 % len(args)]
|
|
|
|
|
2017-02-01 20:47:17 +00:00
|
|
|
def changed(self, *value):
|
|
|
|
"""Checks whether the value has changed since the last call."""
|
|
|
|
if self._last_checked_value != value:
|
|
|
|
self._last_checked_value = value
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2008-04-09 10:14:24 +00:00
|
|
|
first = property(lambda x: x.index0 == 0)
|
2012-01-24 23:42:54 +00:00
|
|
|
last = property(lambda x: x._after is _last_iteration)
|
2008-04-09 10:14:24 +00:00
|
|
|
index = property(lambda x: x.index0 + 1)
|
2008-04-18 09:30:37 +00:00
|
|
|
revindex = property(lambda x: x.length - x.index0)
|
|
|
|
revindex0 = property(lambda x: x.length - x.index)
|
2013-05-20 08:26:57 +00:00
|
|
|
depth = property(lambda x: x.depth0 + 1)
|
2008-04-16 12:21:57 +00:00
|
|
|
|
2017-02-01 20:05:03 +00:00
|
|
|
@property
|
|
|
|
def previtem(self):
|
|
|
|
if self._before is _first_iteration:
|
|
|
|
return self._undefined('there is no previous item')
|
|
|
|
return self._before
|
|
|
|
|
|
|
|
@property
|
|
|
|
def nextitem(self):
|
|
|
|
if self._after is _last_iteration:
|
|
|
|
return self._undefined('there is no next item')
|
|
|
|
return self._after
|
|
|
|
|
2008-04-16 12:21:57 +00:00
|
|
|
def __len__(self):
|
|
|
|
return self.length
|
2008-04-09 12:02:55 +00:00
|
|
|
|
2009-02-24 21:58:00 +00:00
|
|
|
@internalcode
|
2008-05-11 21:42:19 +00:00
|
|
|
def loop(self, iterable):
|
2008-05-11 21:21:16 +00:00
|
|
|
if self._recurse is None:
|
|
|
|
raise TypeError('Tried to call non recursive loop. Maybe you '
|
2008-05-11 21:42:19 +00:00
|
|
|
"forgot the 'recursive' modifier.")
|
2013-05-20 08:26:57 +00:00
|
|
|
return self._recurse(iterable, self._recurse, self.depth0 + 1)
|
2008-05-11 21:21:16 +00:00
|
|
|
|
2008-05-11 21:42:19 +00:00
|
|
|
# a nifty trick to enhance the error message if someone tried to call
|
2019-06-21 18:24:08 +00:00
|
|
|
# the loop without or with too many arguments.
|
2010-02-16 23:52:42 +00:00
|
|
|
__call__ = loop
|
|
|
|
del loop
|
2008-05-11 21:42:19 +00:00
|
|
|
|
2008-04-16 12:21:57 +00:00
|
|
|
def __repr__(self):
|
2008-04-27 19:28:03 +00:00
|
|
|
return '<%s %r/%r>' % (
|
|
|
|
self.__class__.__name__,
|
|
|
|
self.index,
|
|
|
|
self.length
|
|
|
|
)
|
2008-04-16 12:21:57 +00:00
|
|
|
|
2008-04-09 10:14:24 +00:00
|
|
|
|
2016-12-28 19:06:34 +00:00
|
|
|
class LoopContext(LoopContextBase):
|
|
|
|
|
2017-02-01 20:05:03 +00:00
|
|
|
def __init__(self, iterable, undefined, recurse=None, depth0=0):
|
|
|
|
LoopContextBase.__init__(self, undefined, recurse, depth0)
|
2016-12-28 19:06:34 +00:00
|
|
|
self._iterator = iter(iterable)
|
2016-12-28 20:49:00 +00:00
|
|
|
|
|
|
|
# try to get the length of the iterable early. This must be done
|
|
|
|
# here because there are some broken iterators around where there
|
|
|
|
# __len__ is the number of iterations left (i'm looking at your
|
|
|
|
# listreverseiterator!).
|
|
|
|
try:
|
|
|
|
self._length = len(iterable)
|
|
|
|
except (TypeError, AttributeError):
|
|
|
|
self._length = None
|
2016-12-28 19:06:34 +00:00
|
|
|
self._after = self._safe_next()
|
|
|
|
|
2016-12-28 20:49:00 +00:00
|
|
|
@property
|
|
|
|
def length(self):
|
|
|
|
if self._length is None:
|
|
|
|
# if was not possible to get the length of the iterator when
|
|
|
|
# the loop context was created (ie: iterating over a generator)
|
|
|
|
# we have to convert the iterable into a sequence and use the
|
|
|
|
# length of that + the number of iterations so far.
|
|
|
|
iterable = tuple(self._iterator)
|
|
|
|
self._iterator = iter(iterable)
|
|
|
|
iterations_done = self.index0 + 2
|
|
|
|
self._length = len(iterable) + iterations_done
|
|
|
|
return self._length
|
|
|
|
|
2016-12-28 19:06:34 +00:00
|
|
|
def __iter__(self):
|
|
|
|
return LoopContextIterator(self)
|
|
|
|
|
|
|
|
def _safe_next(self):
|
|
|
|
try:
|
|
|
|
return next(self._iterator)
|
|
|
|
except StopIteration:
|
|
|
|
return _last_iteration
|
|
|
|
|
|
|
|
|
2013-05-20 00:51:26 +00:00
|
|
|
@implements_iterator
|
|
|
|
class LoopContextIterator(object):
|
2008-05-18 18:25:28 +00:00
|
|
|
"""The iterator for a loop context."""
|
|
|
|
__slots__ = ('context',)
|
|
|
|
|
|
|
|
def __init__(self, context):
|
|
|
|
self.context = context
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return self
|
|
|
|
|
2013-05-17 22:06:22 +00:00
|
|
|
def __next__(self):
|
2008-05-18 18:25:28 +00:00
|
|
|
ctx = self.context
|
|
|
|
ctx.index0 += 1
|
2012-01-24 23:42:54 +00:00
|
|
|
if ctx._after is _last_iteration:
|
|
|
|
raise StopIteration()
|
2017-02-01 20:05:03 +00:00
|
|
|
ctx._before = ctx._current
|
|
|
|
ctx._current = ctx._after
|
2012-01-24 22:19:08 +00:00
|
|
|
ctx._after = ctx._safe_next()
|
2017-02-01 20:05:03 +00:00
|
|
|
return ctx._current, ctx
|
2008-05-18 18:25:28 +00:00
|
|
|
|
|
|
|
|
2008-04-08 16:09:13 +00:00
|
|
|
class Macro(object):
|
2010-06-05 12:32:06 +00:00
|
|
|
"""Wraps a macro function."""
|
2008-04-08 16:09:13 +00:00
|
|
|
|
2017-01-03 17:19:31 +00:00
|
|
|
def __init__(self, environment, func, name, arguments,
|
2017-01-06 13:29:23 +00:00
|
|
|
catch_kwargs, catch_varargs, caller,
|
|
|
|
default_autoescape=None):
|
2008-04-14 20:53:58 +00:00
|
|
|
self._environment = environment
|
2008-04-12 12:19:36 +00:00
|
|
|
self._func = func
|
2008-04-29 11:43:16 +00:00
|
|
|
self._argument_count = len(arguments)
|
2008-04-08 16:09:13 +00:00
|
|
|
self.name = name
|
|
|
|
self.arguments = arguments
|
2008-04-25 09:44:59 +00:00
|
|
|
self.catch_kwargs = catch_kwargs
|
|
|
|
self.catch_varargs = catch_varargs
|
2008-04-12 12:19:36 +00:00
|
|
|
self.caller = caller
|
2017-01-08 01:16:41 +00:00
|
|
|
self.explicit_caller = 'caller' in arguments
|
2017-01-06 13:29:23 +00:00
|
|
|
if default_autoescape is None:
|
|
|
|
default_autoescape = environment.autoescape
|
|
|
|
self._default_autoescape = default_autoescape
|
2008-04-08 16:09:13 +00:00
|
|
|
|
2009-02-24 21:58:00 +00:00
|
|
|
@internalcode
|
2017-01-06 13:29:23 +00:00
|
|
|
@evalcontextfunction
|
2008-04-08 16:09:13 +00:00
|
|
|
def __call__(self, *args, **kwargs):
|
2017-01-06 13:29:23 +00:00
|
|
|
# This requires a bit of explanation, In the past we used to
|
|
|
|
# decide largely based on compile-time information if a macro is
|
|
|
|
# safe or unsafe. While there was a volatile mode it was largely
|
|
|
|
# unused for deciding on escaping. This turns out to be
|
|
|
|
# problemtic for macros because if a macro is safe or not not so
|
|
|
|
# much depends on the escape mode when it was defined but when it
|
|
|
|
# was used.
|
|
|
|
#
|
|
|
|
# Because however we export macros from the module system and
|
|
|
|
# there are historic callers that do not pass an eval context (and
|
|
|
|
# will continue to not pass one), we need to perform an instance
|
|
|
|
# check here.
|
|
|
|
#
|
|
|
|
# This is considered safe because an eval context is not a valid
|
2019-07-07 13:07:29 +00:00
|
|
|
# argument to callables otherwise anyway. Worst case here is
|
2017-01-06 13:29:23 +00:00
|
|
|
# that if no eval context is passed we fall back to the compile
|
|
|
|
# time autoescape flag.
|
|
|
|
if args and isinstance(args[0], EvalContext):
|
|
|
|
autoescape = args[0].autoescape
|
|
|
|
args = args[1:]
|
|
|
|
else:
|
|
|
|
autoescape = self._default_autoescape
|
|
|
|
|
2010-06-05 12:32:06 +00:00
|
|
|
# try to consume the positional arguments
|
|
|
|
arguments = list(args[:self._argument_count])
|
|
|
|
off = len(arguments)
|
|
|
|
|
2017-01-08 01:16:41 +00:00
|
|
|
# For information why this is necessary refer to the handling
|
|
|
|
# of caller in the `macro_body` handler in the compiler.
|
|
|
|
found_caller = False
|
|
|
|
|
2010-06-05 12:32:06 +00:00
|
|
|
# if the number of arguments consumed is not the number of
|
|
|
|
# arguments expected we start filling in keyword arguments
|
|
|
|
# and defaults.
|
|
|
|
if off != self._argument_count:
|
|
|
|
for idx, name in enumerate(self.arguments[len(arguments):]):
|
2008-04-08 16:49:56 +00:00
|
|
|
try:
|
|
|
|
value = kwargs.pop(name)
|
2010-06-05 12:32:06 +00:00
|
|
|
except KeyError:
|
2017-01-03 17:19:31 +00:00
|
|
|
value = missing
|
2017-01-08 01:16:41 +00:00
|
|
|
if name == 'caller':
|
|
|
|
found_caller = True
|
2010-06-05 12:32:06 +00:00
|
|
|
arguments.append(value)
|
2017-01-08 01:16:41 +00:00
|
|
|
else:
|
|
|
|
found_caller = self.explicit_caller
|
2008-04-26 14:26:52 +00:00
|
|
|
|
|
|
|
# it's important that the order of these arguments does not change
|
|
|
|
# if not also changed in the compiler's `function_scoping` method.
|
|
|
|
# the order is caller, keyword arguments, positional arguments!
|
2017-01-08 01:16:41 +00:00
|
|
|
if self.caller and not found_caller:
|
2008-04-12 12:19:36 +00:00
|
|
|
caller = kwargs.pop('caller', None)
|
|
|
|
if caller is None:
|
2008-05-01 10:49:53 +00:00
|
|
|
caller = self._environment.undefined('No caller defined',
|
|
|
|
name='caller')
|
2008-04-26 14:26:52 +00:00
|
|
|
arguments.append(caller)
|
2017-01-08 01:16:41 +00:00
|
|
|
|
2008-04-25 09:44:59 +00:00
|
|
|
if self.catch_kwargs:
|
2008-04-26 14:26:52 +00:00
|
|
|
arguments.append(kwargs)
|
2008-04-25 09:44:59 +00:00
|
|
|
elif kwargs:
|
2017-01-08 01:16:41 +00:00
|
|
|
if 'caller' in kwargs:
|
|
|
|
raise TypeError('macro %r was invoked with two values for '
|
|
|
|
'the special caller argument. This is '
|
|
|
|
'most likely a bug.' % self.name)
|
2008-04-25 09:44:59 +00:00
|
|
|
raise TypeError('macro %r takes no keyword argument %r' %
|
2009-08-05 18:25:06 +00:00
|
|
|
(self.name, next(iter(kwargs))))
|
2008-04-25 09:44:59 +00:00
|
|
|
if self.catch_varargs:
|
2008-04-29 11:43:16 +00:00
|
|
|
arguments.append(args[self._argument_count:])
|
2008-05-01 10:49:53 +00:00
|
|
|
elif len(args) > self._argument_count:
|
|
|
|
raise TypeError('macro %r takes not more than %d argument(s)' %
|
|
|
|
(self.name, len(self.arguments)))
|
2017-01-06 13:29:23 +00:00
|
|
|
|
2017-01-28 14:33:09 +00:00
|
|
|
return self._invoke(arguments, autoescape)
|
|
|
|
|
|
|
|
def _invoke(self, arguments, autoescape):
|
|
|
|
"""This method is being swapped out by the async implementation."""
|
2017-01-06 13:29:23 +00:00
|
|
|
rv = self._func(*arguments)
|
|
|
|
if autoescape:
|
|
|
|
rv = Markup(rv)
|
|
|
|
return rv
|
2008-04-12 12:19:36 +00:00
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return '<%s %s>' % (
|
|
|
|
self.__class__.__name__,
|
|
|
|
self.name is None and 'anonymous' or repr(self.name)
|
|
|
|
)
|
2008-04-09 12:02:55 +00:00
|
|
|
|
|
|
|
|
2013-05-20 00:51:26 +00:00
|
|
|
@implements_to_string
|
|
|
|
class Undefined(object):
|
2008-04-28 10:20:12 +00:00
|
|
|
"""The default undefined type. This undefined type can be printed and
|
2019-05-08 14:47:33 +00:00
|
|
|
iterated over, but every other access will raise an :exc:`UndefinedError`:
|
2008-04-28 10:20:12 +00:00
|
|
|
|
|
|
|
>>> foo = Undefined(name='foo')
|
|
|
|
>>> str(foo)
|
|
|
|
''
|
|
|
|
>>> not foo
|
|
|
|
True
|
|
|
|
>>> foo + 42
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2015-03-22 13:22:40 +00:00
|
|
|
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
2008-04-14 20:53:58 +00:00
|
|
|
"""
|
2008-05-07 10:17:18 +00:00
|
|
|
__slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
|
|
|
|
'_undefined_exception')
|
2008-04-09 12:02:55 +00:00
|
|
|
|
2010-04-12 11:51:33 +00:00
|
|
|
def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):
|
2008-04-17 16:44:07 +00:00
|
|
|
self._undefined_hint = hint
|
|
|
|
self._undefined_obj = obj
|
|
|
|
self._undefined_name = name
|
2008-05-07 10:17:18 +00:00
|
|
|
self._undefined_exception = exc
|
2008-04-09 12:02:55 +00:00
|
|
|
|
2009-02-24 21:58:00 +00:00
|
|
|
@internalcode
|
2008-05-28 09:26:59 +00:00
|
|
|
def _fail_with_undefined_error(self, *args, **kwargs):
|
|
|
|
"""Regular callback function for undefined objects that raises an
|
2019-05-08 14:47:33 +00:00
|
|
|
`UndefinedError` on call.
|
2008-05-28 09:26:59 +00:00
|
|
|
"""
|
|
|
|
if self._undefined_hint is None:
|
2010-04-12 11:51:33 +00:00
|
|
|
if self._undefined_obj is missing:
|
2008-05-28 09:26:59 +00:00
|
|
|
hint = '%r is undefined' % self._undefined_name
|
2013-05-19 13:16:13 +00:00
|
|
|
elif not isinstance(self._undefined_name, string_types):
|
2010-04-12 13:49:59 +00:00
|
|
|
hint = '%s has no element %r' % (
|
|
|
|
object_type_repr(self._undefined_obj),
|
2008-05-28 09:26:59 +00:00
|
|
|
self._undefined_name
|
|
|
|
)
|
|
|
|
else:
|
2010-04-12 13:49:59 +00:00
|
|
|
hint = '%r has no attribute %r' % (
|
|
|
|
object_type_repr(self._undefined_obj),
|
2008-05-28 09:26:59 +00:00
|
|
|
self._undefined_name
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
hint = self._undefined_hint
|
|
|
|
raise self._undefined_exception(hint)
|
|
|
|
|
2010-11-19 12:51:38 +00:00
|
|
|
@internalcode
|
|
|
|
def __getattr__(self, name):
|
|
|
|
if name[:2] == '__':
|
|
|
|
raise AttributeError(name)
|
|
|
|
return self._fail_with_undefined_error()
|
|
|
|
|
2008-04-14 20:53:58 +00:00
|
|
|
__add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
|
2014-06-06 16:00:04 +00:00
|
|
|
__truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
|
|
|
|
__mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
|
|
|
|
__getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
|
2016-01-07 23:23:26 +00:00
|
|
|
__float__ = __complex__ = __pow__ = __rpow__ = __sub__ = \
|
2017-01-03 18:33:25 +00:00
|
|
|
__rsub__ = _fail_with_undefined_error
|
2008-04-14 20:53:58 +00:00
|
|
|
|
2013-08-07 11:48:37 +00:00
|
|
|
def __eq__(self, other):
|
|
|
|
return type(self) is type(other)
|
|
|
|
|
|
|
|
def __ne__(self, other):
|
|
|
|
return not self.__eq__(other)
|
|
|
|
|
|
|
|
def __hash__(self):
|
|
|
|
return id(type(self))
|
|
|
|
|
2013-05-20 00:51:26 +00:00
|
|
|
def __str__(self):
|
2008-04-24 19:54:44 +00:00
|
|
|
return u''
|
|
|
|
|
2008-04-09 12:02:55 +00:00
|
|
|
def __len__(self):
|
|
|
|
return 0
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
if 0:
|
|
|
|
yield None
|
2008-04-14 20:53:58 +00:00
|
|
|
|
|
|
|
def __nonzero__(self):
|
|
|
|
return False
|
2014-06-06 16:17:05 +00:00
|
|
|
__bool__ = __nonzero__
|
2008-04-14 20:53:58 +00:00
|
|
|
|
2008-05-28 09:26:59 +00:00
|
|
|
def __repr__(self):
|
|
|
|
return 'Undefined'
|
|
|
|
|
2008-04-14 20:53:58 +00:00
|
|
|
|
2014-06-06 16:00:04 +00:00
|
|
|
def make_logging_undefined(logger=None, base=None):
|
2014-06-06 16:14:45 +00:00
|
|
|
"""Given a logger object this returns a new undefined class that will
|
|
|
|
log certain failures. It will log iterations and printing. If no
|
|
|
|
logger is given a default logger is created.
|
|
|
|
|
|
|
|
Example::
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
LoggingUndefined = make_logging_undefined(
|
|
|
|
logger=logger,
|
|
|
|
base=Undefined
|
|
|
|
)
|
|
|
|
|
|
|
|
.. versionadded:: 2.8
|
|
|
|
|
|
|
|
:param logger: the logger to use. If not provided, a default logger
|
|
|
|
is created.
|
|
|
|
:param base: the base class to add logging functionality to. This
|
|
|
|
defaults to :class:`Undefined`.
|
2014-06-06 16:00:04 +00:00
|
|
|
"""
|
|
|
|
if logger is None:
|
|
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
logger.addHandler(logging.StreamHandler(sys.stderr))
|
|
|
|
if base is None:
|
|
|
|
base = Undefined
|
|
|
|
|
2014-06-06 16:14:45 +00:00
|
|
|
def _log_message(undef):
|
|
|
|
if undef._undefined_hint is None:
|
|
|
|
if undef._undefined_obj is missing:
|
|
|
|
hint = '%s is undefined' % undef._undefined_name
|
|
|
|
elif not isinstance(undef._undefined_name, string_types):
|
|
|
|
hint = '%s has no element %s' % (
|
|
|
|
object_type_repr(undef._undefined_obj),
|
|
|
|
undef._undefined_name)
|
|
|
|
else:
|
|
|
|
hint = '%s has no attribute %s' % (
|
|
|
|
object_type_repr(undef._undefined_obj),
|
|
|
|
undef._undefined_name)
|
|
|
|
else:
|
|
|
|
hint = undef._undefined_hint
|
|
|
|
logger.warning('Template variable warning: %s', hint)
|
|
|
|
|
2014-06-06 16:00:04 +00:00
|
|
|
class LoggingUndefined(base):
|
2014-06-06 16:14:45 +00:00
|
|
|
|
|
|
|
def _fail_with_undefined_error(self, *args, **kwargs):
|
|
|
|
try:
|
|
|
|
return base._fail_with_undefined_error(self, *args, **kwargs)
|
|
|
|
except self._undefined_exception as e:
|
|
|
|
logger.error('Template variable error: %s', str(e))
|
|
|
|
raise e
|
|
|
|
|
2014-06-06 16:00:04 +00:00
|
|
|
def __str__(self):
|
2014-06-06 16:14:45 +00:00
|
|
|
rv = base.__str__(self)
|
|
|
|
_log_message(self)
|
|
|
|
return rv
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
rv = base.__iter__(self)
|
|
|
|
_log_message(self)
|
|
|
|
return rv
|
|
|
|
|
2014-06-06 16:17:05 +00:00
|
|
|
if PY2:
|
|
|
|
def __nonzero__(self):
|
|
|
|
rv = base.__nonzero__(self)
|
|
|
|
_log_message(self)
|
|
|
|
return rv
|
|
|
|
|
|
|
|
def __unicode__(self):
|
|
|
|
rv = base.__unicode__(self)
|
|
|
|
_log_message(self)
|
|
|
|
return rv
|
|
|
|
else:
|
|
|
|
def __bool__(self):
|
|
|
|
rv = base.__bool__(self)
|
|
|
|
_log_message(self)
|
|
|
|
return rv
|
2014-06-06 16:00:04 +00:00
|
|
|
|
|
|
|
return LoggingUndefined
|
|
|
|
|
|
|
|
|
2019-05-08 14:47:33 +00:00
|
|
|
# No @implements_to_string decorator here because __str__
|
|
|
|
# is not overwritten from Undefined in this class.
|
|
|
|
# This would cause a recursion error in Python 2.
|
|
|
|
class ChainableUndefined(Undefined):
|
|
|
|
"""An undefined that is chainable, where both
|
|
|
|
__getattr__ and __getitem__ return itself rather than
|
|
|
|
raising an :exc:`UndefinedError`:
|
|
|
|
|
|
|
|
>>> foo = ChainableUndefined(name='foo')
|
|
|
|
>>> str(foo.bar['baz'])
|
|
|
|
''
|
|
|
|
>>> foo.bar['baz'] + 42
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
|
|
|
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
|
|
|
|
|
|
|
.. versionadded:: 2.11
|
|
|
|
"""
|
|
|
|
__slots__ = ()
|
|
|
|
|
|
|
|
def __getattr__(self, _):
|
|
|
|
return self
|
|
|
|
|
|
|
|
__getitem__ = __getattr__
|
|
|
|
|
|
|
|
|
2013-05-20 00:51:26 +00:00
|
|
|
@implements_to_string
|
2008-04-14 20:53:58 +00:00
|
|
|
class DebugUndefined(Undefined):
|
2008-04-28 10:20:12 +00:00
|
|
|
"""An undefined that returns the debug info when printed.
|
|
|
|
|
|
|
|
>>> foo = DebugUndefined(name='foo')
|
|
|
|
>>> str(foo)
|
|
|
|
'{{ foo }}'
|
|
|
|
>>> not foo
|
|
|
|
True
|
|
|
|
>>> foo + 42
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2015-03-22 13:22:40 +00:00
|
|
|
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
2008-04-28 10:20:12 +00:00
|
|
|
"""
|
2008-04-26 16:30:19 +00:00
|
|
|
__slots__ = ()
|
2008-04-14 20:53:58 +00:00
|
|
|
|
2013-05-20 00:51:26 +00:00
|
|
|
def __str__(self):
|
2008-04-17 16:44:07 +00:00
|
|
|
if self._undefined_hint is None:
|
2010-04-12 11:51:33 +00:00
|
|
|
if self._undefined_obj is missing:
|
2008-04-17 16:44:07 +00:00
|
|
|
return u'{{ %s }}' % self._undefined_name
|
|
|
|
return '{{ no such element: %s[%r] }}' % (
|
2010-04-12 13:49:59 +00:00
|
|
|
object_type_repr(self._undefined_obj),
|
2008-04-17 16:44:07 +00:00
|
|
|
self._undefined_name
|
|
|
|
)
|
|
|
|
return u'{{ undefined value printed: %s }}' % self._undefined_hint
|
2008-04-14 20:53:58 +00:00
|
|
|
|
|
|
|
|
2013-05-20 00:51:26 +00:00
|
|
|
@implements_to_string
|
2008-04-14 20:53:58 +00:00
|
|
|
class StrictUndefined(Undefined):
|
2008-04-24 19:54:44 +00:00
|
|
|
"""An undefined that barks on print and iteration as well as boolean
|
2008-04-26 16:30:19 +00:00
|
|
|
tests and all kinds of comparisons. In other words: you can do nothing
|
|
|
|
with it except checking if it's defined using the `defined` test.
|
2008-04-28 10:20:12 +00:00
|
|
|
|
|
|
|
>>> foo = StrictUndefined(name='foo')
|
|
|
|
>>> str(foo)
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2015-03-22 13:22:40 +00:00
|
|
|
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
2008-04-28 10:20:12 +00:00
|
|
|
>>> not foo
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2015-03-22 13:22:40 +00:00
|
|
|
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
2008-04-28 10:20:12 +00:00
|
|
|
>>> foo + 42
|
|
|
|
Traceback (most recent call last):
|
|
|
|
...
|
2015-03-22 13:22:40 +00:00
|
|
|
jinja2.exceptions.UndefinedError: 'foo' is undefined
|
2008-04-17 17:04:44 +00:00
|
|
|
"""
|
2008-04-26 16:30:19 +00:00
|
|
|
__slots__ = ()
|
2013-05-20 00:51:26 +00:00
|
|
|
__iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \
|
2013-08-07 11:48:37 +00:00
|
|
|
__ne__ = __bool__ = __hash__ = \
|
|
|
|
Undefined._fail_with_undefined_error
|
2008-04-26 16:30:19 +00:00
|
|
|
|
2008-04-14 20:53:58 +00:00
|
|
|
|
2008-04-26 16:30:19 +00:00
|
|
|
# remove remaining slots attributes, after the metaclass did the magic they
|
|
|
|
# are unneeded and irritating as they contain wrong data for the subclasses.
|
2019-05-08 14:47:33 +00:00
|
|
|
del Undefined.__slots__, ChainableUndefined.__slots__, \
|
|
|
|
DebugUndefined.__slots__, StrictUndefined.__slots__
|