You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

813 lines
27 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.runtime
  4. ~~~~~~~~~~~~~~
  5. Runtime helpers.
  6. :copyright: (c) 2017 by the Jinja Team.
  7. :license: BSD.
  8. """
  9. import sys
  10. from itertools import chain
  11. from types import MethodType
  12. from jinja2.nodes import EvalContext, _context_function_types
  13. from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \
  14. internalcode, object_type_repr, evalcontextfunction, Namespace
  15. from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \
  16. TemplateNotFound
  17. from jinja2._compat import imap, text_type, iteritems, \
  18. implements_iterator, implements_to_string, string_types, PY2, \
  19. with_metaclass
  20. # these variables are exported to the template runtime
  21. __all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',
  22. 'TemplateRuntimeError', 'missing', 'concat', 'escape',
  23. 'markup_join', 'unicode_join', 'to_string', 'identity',
  24. 'TemplateNotFound', 'Namespace']
  25. #: the name of the function that is used to convert something into
  26. #: a string. We can just use the text type here.
  27. to_string = text_type
  28. #: the identity function. Useful for certain things in the environment
  29. identity = lambda x: x
  30. _first_iteration = object()
  31. _last_iteration = object()
  32. def markup_join(seq):
  33. """Concatenation that escapes if necessary and converts to unicode."""
  34. buf = []
  35. iterator = imap(soft_unicode, seq)
  36. for arg in iterator:
  37. buf.append(arg)
  38. if hasattr(arg, '__html__'):
  39. return Markup(u'').join(chain(buf, iterator))
  40. return concat(buf)
  41. def unicode_join(seq):
  42. """Simple args to unicode conversion and concatenation."""
  43. return concat(imap(text_type, seq))
  44. def new_context(environment, template_name, blocks, vars=None,
  45. shared=None, globals=None, locals=None):
  46. """Internal helper to for context creation."""
  47. if vars is None:
  48. vars = {}
  49. if shared:
  50. parent = vars
  51. else:
  52. parent = dict(globals or (), **vars)
  53. if locals:
  54. # if the parent is shared a copy should be created because
  55. # we don't want to modify the dict passed
  56. if shared:
  57. parent = dict(parent)
  58. for key, value in iteritems(locals):
  59. if value is not missing:
  60. parent[key] = value
  61. return environment.context_class(environment, parent, template_name,
  62. blocks)
  63. class TemplateReference(object):
  64. """The `self` in templates."""
  65. def __init__(self, context):
  66. self.__context = context
  67. def __getitem__(self, name):
  68. blocks = self.__context.blocks[name]
  69. return BlockReference(name, self.__context, blocks, 0)
  70. def __repr__(self):
  71. return '<%s %r>' % (
  72. self.__class__.__name__,
  73. self.__context.name
  74. )
  75. def _get_func(x):
  76. return getattr(x, '__func__', x)
  77. class ContextMeta(type):
  78. def __new__(cls, name, bases, d):
  79. rv = type.__new__(cls, name, bases, d)
  80. if bases == ():
  81. return rv
  82. resolve = _get_func(rv.resolve)
  83. default_resolve = _get_func(Context.resolve)
  84. resolve_or_missing = _get_func(rv.resolve_or_missing)
  85. default_resolve_or_missing = _get_func(Context.resolve_or_missing)
  86. # If we have a changed resolve but no changed default or missing
  87. # resolve we invert the call logic.
  88. if resolve is not default_resolve and \
  89. resolve_or_missing is default_resolve_or_missing:
  90. rv._legacy_resolve_mode = True
  91. elif resolve is default_resolve and \
  92. resolve_or_missing is default_resolve_or_missing:
  93. rv._fast_resolve_mode = True
  94. return rv
  95. def resolve_or_missing(context, key, missing=missing):
  96. if key in context.vars:
  97. return context.vars[key]
  98. if key in context.parent:
  99. return context.parent[key]
  100. return missing
  101. class Context(with_metaclass(ContextMeta)):
  102. """The template context holds the variables of a template. It stores the
  103. values passed to the template and also the names the template exports.
  104. Creating instances is neither supported nor useful as it's created
  105. automatically at various stages of the template evaluation and should not
  106. be created by hand.
  107. The context is immutable. Modifications on :attr:`parent` **must not**
  108. happen and modifications on :attr:`vars` are allowed from generated
  109. template code only. Template filters and global functions marked as
  110. :func:`contextfunction`\\s get the active context passed as first argument
  111. and are allowed to access the context read-only.
  112. The template context supports read only dict operations (`get`,
  113. `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,
  114. `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`
  115. method that doesn't fail with a `KeyError` but returns an
  116. :class:`Undefined` object for missing variables.
  117. """
  118. # XXX: we want to eventually make this be a deprecation warning and
  119. # remove it.
  120. _legacy_resolve_mode = False
  121. _fast_resolve_mode = False
  122. def __init__(self, environment, parent, name, blocks):
  123. self.parent = parent
  124. self.vars = {}
  125. self.environment = environment
  126. self.eval_ctx = EvalContext(self.environment, name)
  127. self.exported_vars = set()
  128. self.name = name
  129. # create the initial mapping of blocks. Whenever template inheritance
  130. # takes place the runtime will update this mapping with the new blocks
  131. # from the template.
  132. self.blocks = dict((k, [v]) for k, v in iteritems(blocks))
  133. # In case we detect the fast resolve mode we can set up an alias
  134. # here that bypasses the legacy code logic.
  135. if self._fast_resolve_mode:
  136. self.resolve_or_missing = MethodType(resolve_or_missing, self)
  137. def super(self, name, current):
  138. """Render a parent block."""
  139. try:
  140. blocks = self.blocks[name]
  141. index = blocks.index(current) + 1
  142. blocks[index]
  143. except LookupError:
  144. return self.environment.undefined('there is no parent block '
  145. 'called %r.' % name,
  146. name='super')
  147. return BlockReference(name, self, blocks, index)
  148. def get(self, key, default=None):
  149. """Returns an item from the template context, if it doesn't exist
  150. `default` is returned.
  151. """
  152. try:
  153. return self[key]
  154. except KeyError:
  155. return default
  156. def resolve(self, key):
  157. """Looks up a variable like `__getitem__` or `get` but returns an
  158. :class:`Undefined` object with the name of the name looked up.
  159. """
  160. if self._legacy_resolve_mode:
  161. rv = resolve_or_missing(self, key)
  162. else:
  163. rv = self.resolve_or_missing(key)
  164. if rv is missing:
  165. return self.environment.undefined(name=key)
  166. return rv
  167. def resolve_or_missing(self, key):
  168. """Resolves a variable like :meth:`resolve` but returns the
  169. special `missing` value if it cannot be found.
  170. """
  171. if self._legacy_resolve_mode:
  172. rv = self.resolve(key)
  173. if isinstance(rv, Undefined):
  174. rv = missing
  175. return rv
  176. return resolve_or_missing(self, key)
  177. def get_exported(self):
  178. """Get a new dict with the exported variables."""
  179. return dict((k, self.vars[k]) for k in self.exported_vars)
  180. def get_all(self):
  181. """Return the complete context as dict including the exported
  182. variables. For optimizations reasons this might not return an
  183. actual copy so be careful with using it.
  184. """
  185. if not self.vars:
  186. return self.parent
  187. if not self.parent:
  188. return self.vars
  189. return dict(self.parent, **self.vars)
  190. @internalcode
  191. def call(__self, __obj, *args, **kwargs):
  192. """Call the callable with the arguments and keyword arguments
  193. provided but inject the active context or environment as first
  194. argument if the callable is a :func:`contextfunction` or
  195. :func:`environmentfunction`.
  196. """
  197. if __debug__:
  198. __traceback_hide__ = True # noqa
  199. # Allow callable classes to take a context
  200. if hasattr(__obj, '__call__'):
  201. fn = __obj.__call__
  202. for fn_type in ('contextfunction',
  203. 'evalcontextfunction',
  204. 'environmentfunction'):
  205. if hasattr(fn, fn_type):
  206. __obj = fn
  207. break
  208. if isinstance(__obj, _context_function_types):
  209. if getattr(__obj, 'contextfunction', 0):
  210. args = (__self,) + args
  211. elif getattr(__obj, 'evalcontextfunction', 0):
  212. args = (__self.eval_ctx,) + args
  213. elif getattr(__obj, 'environmentfunction', 0):
  214. args = (__self.environment,) + args
  215. try:
  216. return __obj(*args, **kwargs)
  217. except StopIteration:
  218. return __self.environment.undefined('value was undefined because '
  219. 'a callable raised a '
  220. 'StopIteration exception')
  221. def derived(self, locals=None):
  222. """Internal helper function to create a derived context. This is
  223. used in situations where the system needs a new context in the same
  224. template that is independent.
  225. """
  226. context = new_context(self.environment, self.name, {},
  227. self.get_all(), True, None, locals)
  228. context.eval_ctx = self.eval_ctx
  229. context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))
  230. return context
  231. def _all(meth):
  232. proxy = lambda self: getattr(self.get_all(), meth)()
  233. proxy.__doc__ = getattr(dict, meth).__doc__
  234. proxy.__name__ = meth
  235. return proxy
  236. keys = _all('keys')
  237. values = _all('values')
  238. items = _all('items')
  239. # not available on python 3
  240. if PY2:
  241. iterkeys = _all('iterkeys')
  242. itervalues = _all('itervalues')
  243. iteritems = _all('iteritems')
  244. del _all
  245. def __contains__(self, name):
  246. return name in self.vars or name in self.parent
  247. def __getitem__(self, key):
  248. """Lookup a variable or raise `KeyError` if the variable is
  249. undefined.
  250. """
  251. item = self.resolve_or_missing(key)
  252. if item is missing:
  253. raise KeyError(key)
  254. return item
  255. def __repr__(self):
  256. return '<%s %s of %r>' % (
  257. self.__class__.__name__,
  258. repr(self.get_all()),
  259. self.name
  260. )
  261. # register the context as mapping if possible
  262. try:
  263. from collections import Mapping
  264. Mapping.register(Context)
  265. except ImportError:
  266. pass
  267. class BlockReference(object):
  268. """One block on a template reference."""
  269. def __init__(self, name, context, stack, depth):
  270. self.name = name
  271. self._context = context
  272. self._stack = stack
  273. self._depth = depth
  274. @property
  275. def super(self):
  276. """Super the block."""
  277. if self._depth + 1 >= len(self._stack):
  278. return self._context.environment. \
  279. undefined('there is no parent block called %r.' %
  280. self.name, name='super')
  281. return BlockReference(self.name, self._context, self._stack,
  282. self._depth + 1)
  283. @internalcode
  284. def __call__(self):
  285. rv = concat(self._stack[self._depth](self._context))
  286. if self._context.eval_ctx.autoescape:
  287. rv = Markup(rv)
  288. return rv
  289. class LoopContextBase(object):
  290. """A loop context for dynamic iteration."""
  291. _before = _first_iteration
  292. _current = _first_iteration
  293. _after = _last_iteration
  294. _length = None
  295. def __init__(self, undefined, recurse=None, depth0=0):
  296. self._undefined = undefined
  297. self._recurse = recurse
  298. self.index0 = -1
  299. self.depth0 = depth0
  300. self._last_checked_value = missing
  301. def cycle(self, *args):
  302. """Cycles among the arguments with the current loop index."""
  303. if not args:
  304. raise TypeError('no items for cycling given')
  305. return args[self.index0 % len(args)]
  306. def changed(self, *value):
  307. """Checks whether the value has changed since the last call."""
  308. if self._last_checked_value != value:
  309. self._last_checked_value = value
  310. return True
  311. return False
  312. first = property(lambda x: x.index0 == 0)
  313. last = property(lambda x: x._after is _last_iteration)
  314. index = property(lambda x: x.index0 + 1)
  315. revindex = property(lambda x: x.length - x.index0)
  316. revindex0 = property(lambda x: x.length - x.index)
  317. depth = property(lambda x: x.depth0 + 1)
  318. @property
  319. def previtem(self):
  320. if self._before is _first_iteration:
  321. return self._undefined('there is no previous item')
  322. return self._before
  323. @property
  324. def nextitem(self):
  325. if self._after is _last_iteration:
  326. return self._undefined('there is no next item')
  327. return self._after
  328. def __len__(self):
  329. return self.length
  330. @internalcode
  331. def loop(self, iterable):
  332. if self._recurse is None:
  333. raise TypeError('Tried to call non recursive loop. Maybe you '
  334. "forgot the 'recursive' modifier.")
  335. return self._recurse(iterable, self._recurse, self.depth0 + 1)
  336. # a nifty trick to enhance the error message if someone tried to call
  337. # the the loop without or with too many arguments.
  338. __call__ = loop
  339. del loop
  340. def __repr__(self):
  341. return '<%s %r/%r>' % (
  342. self.__class__.__name__,
  343. self.index,
  344. self.length
  345. )
  346. class LoopContext(LoopContextBase):
  347. def __init__(self, iterable, undefined, recurse=None, depth0=0):
  348. LoopContextBase.__init__(self, undefined, recurse, depth0)
  349. self._iterator = iter(iterable)
  350. # try to get the length of the iterable early. This must be done
  351. # here because there are some broken iterators around where there
  352. # __len__ is the number of iterations left (i'm looking at your
  353. # listreverseiterator!).
  354. try:
  355. self._length = len(iterable)
  356. except (TypeError, AttributeError):
  357. self._length = None
  358. self._after = self._safe_next()
  359. @property
  360. def length(self):
  361. if self._length is None:
  362. # if was not possible to get the length of the iterator when
  363. # the loop context was created (ie: iterating over a generator)
  364. # we have to convert the iterable into a sequence and use the
  365. # length of that + the number of iterations so far.
  366. iterable = tuple(self._iterator)
  367. self._iterator = iter(iterable)
  368. iterations_done = self.index0 + 2
  369. self._length = len(iterable) + iterations_done
  370. return self._length
  371. def __iter__(self):
  372. return LoopContextIterator(self)
  373. def _safe_next(self):
  374. try:
  375. return next(self._iterator)
  376. except StopIteration:
  377. return _last_iteration
  378. @implements_iterator
  379. class LoopContextIterator(object):
  380. """The iterator for a loop context."""
  381. __slots__ = ('context',)
  382. def __init__(self, context):
  383. self.context = context
  384. def __iter__(self):
  385. return self
  386. def __next__(self):
  387. ctx = self.context
  388. ctx.index0 += 1
  389. if ctx._after is _last_iteration:
  390. raise StopIteration()
  391. ctx._before = ctx._current
  392. ctx._current = ctx._after
  393. ctx._after = ctx._safe_next()
  394. return ctx._current, ctx
  395. class Macro(object):
  396. """Wraps a macro function."""
  397. def __init__(self, environment, func, name, arguments,
  398. catch_kwargs, catch_varargs, caller,
  399. default_autoescape=None):
  400. self._environment = environment
  401. self._func = func
  402. self._argument_count = len(arguments)
  403. self.name = name
  404. self.arguments = arguments
  405. self.catch_kwargs = catch_kwargs
  406. self.catch_varargs = catch_varargs
  407. self.caller = caller
  408. self.explicit_caller = 'caller' in arguments
  409. if default_autoescape is None:
  410. default_autoescape = environment.autoescape
  411. self._default_autoescape = default_autoescape
  412. @internalcode
  413. @evalcontextfunction
  414. def __call__(self, *args, **kwargs):
  415. # This requires a bit of explanation, In the past we used to
  416. # decide largely based on compile-time information if a macro is
  417. # safe or unsafe. While there was a volatile mode it was largely
  418. # unused for deciding on escaping. This turns out to be
  419. # problemtic for macros because if a macro is safe or not not so
  420. # much depends on the escape mode when it was defined but when it
  421. # was used.
  422. #
  423. # Because however we export macros from the module system and
  424. # there are historic callers that do not pass an eval context (and
  425. # will continue to not pass one), we need to perform an instance
  426. # check here.
  427. #
  428. # This is considered safe because an eval context is not a valid
  429. # argument to callables otherwise anwyays. Worst case here is
  430. # that if no eval context is passed we fall back to the compile
  431. # time autoescape flag.
  432. if args and isinstance(args[0], EvalContext):
  433. autoescape = args[0].autoescape
  434. args = args[1:]
  435. else:
  436. autoescape = self._default_autoescape
  437. # try to consume the positional arguments
  438. arguments = list(args[:self._argument_count])
  439. off = len(arguments)
  440. # For information why this is necessary refer to the handling
  441. # of caller in the `macro_body` handler in the compiler.
  442. found_caller = False
  443. # if the number of arguments consumed is not the number of
  444. # arguments expected we start filling in keyword arguments
  445. # and defaults.
  446. if off != self._argument_count:
  447. for idx, name in enumerate(self.arguments[len(arguments):]):
  448. try:
  449. value = kwargs.pop(name)
  450. except KeyError:
  451. value = missing
  452. if name == 'caller':
  453. found_caller = True
  454. arguments.append(value)
  455. else:
  456. found_caller = self.explicit_caller
  457. # it's important that the order of these arguments does not change
  458. # if not also changed in the compiler's `function_scoping` method.
  459. # the order is caller, keyword arguments, positional arguments!
  460. if self.caller and not found_caller:
  461. caller = kwargs.pop('caller', None)
  462. if caller is None:
  463. caller = self._environment.undefined('No caller defined',
  464. name='caller')
  465. arguments.append(caller)
  466. if self.catch_kwargs:
  467. arguments.append(kwargs)
  468. elif kwargs:
  469. if 'caller' in kwargs:
  470. raise TypeError('macro %r was invoked with two values for '
  471. 'the special caller argument. This is '
  472. 'most likely a bug.' % self.name)
  473. raise TypeError('macro %r takes no keyword argument %r' %
  474. (self.name, next(iter(kwargs))))
  475. if self.catch_varargs:
  476. arguments.append(args[self._argument_count:])
  477. elif len(args) > self._argument_count:
  478. raise TypeError('macro %r takes not more than %d argument(s)' %
  479. (self.name, len(self.arguments)))
  480. return self._invoke(arguments, autoescape)
  481. def _invoke(self, arguments, autoescape):
  482. """This method is being swapped out by the async implementation."""
  483. rv = self._func(*arguments)
  484. if autoescape:
  485. rv = Markup(rv)
  486. return rv
  487. def __repr__(self):
  488. return '<%s %s>' % (
  489. self.__class__.__name__,
  490. self.name is None and 'anonymous' or repr(self.name)
  491. )
  492. @implements_to_string
  493. class Undefined(object):
  494. """The default undefined type. This undefined type can be printed and
  495. iterated over, but every other access will raise an :exc:`jinja2.exceptions.UndefinedError`:
  496. >>> foo = Undefined(name='foo')
  497. >>> str(foo)
  498. ''
  499. >>> not foo
  500. True
  501. >>> foo + 42
  502. Traceback (most recent call last):
  503. ...
  504. jinja2.exceptions.UndefinedError: 'foo' is undefined
  505. """
  506. __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',
  507. '_undefined_exception')
  508. def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):
  509. self._undefined_hint = hint
  510. self._undefined_obj = obj
  511. self._undefined_name = name
  512. self._undefined_exception = exc
  513. @internalcode
  514. def _fail_with_undefined_error(self, *args, **kwargs):
  515. """Regular callback function for undefined objects that raises an
  516. `jinja2.exceptions.UndefinedError` on call.
  517. """
  518. if self._undefined_hint is None:
  519. if self._undefined_obj is missing:
  520. hint = '%r is undefined' % self._undefined_name
  521. elif not isinstance(self._undefined_name, string_types):
  522. hint = '%s has no element %r' % (
  523. object_type_repr(self._undefined_obj),
  524. self._undefined_name
  525. )
  526. else:
  527. hint = '%r has no attribute %r' % (
  528. object_type_repr(self._undefined_obj),
  529. self._undefined_name
  530. )
  531. else:
  532. hint = self._undefined_hint
  533. raise self._undefined_exception(hint)
  534. @internalcode
  535. def __getattr__(self, name):
  536. if name[:2] == '__':
  537. raise AttributeError(name)
  538. return self._fail_with_undefined_error()
  539. __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \
  540. __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \
  541. __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \
  542. __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \
  543. __float__ = __complex__ = __pow__ = __rpow__ = __sub__ = \
  544. __rsub__ = _fail_with_undefined_error
  545. def __eq__(self, other):
  546. return type(self) is type(other)
  547. def __ne__(self, other):
  548. return not self.__eq__(other)
  549. def __hash__(self):
  550. return id(type(self))
  551. def __str__(self):
  552. return u''
  553. def __len__(self):
  554. return 0
  555. def __iter__(self):
  556. if 0:
  557. yield None
  558. def __nonzero__(self):
  559. return False
  560. __bool__ = __nonzero__
  561. def __repr__(self):
  562. return 'Undefined'
  563. def make_logging_undefined(logger=None, base=None):
  564. """Given a logger object this returns a new undefined class that will
  565. log certain failures. It will log iterations and printing. If no
  566. logger is given a default logger is created.
  567. Example::
  568. logger = logging.getLogger(__name__)
  569. LoggingUndefined = make_logging_undefined(
  570. logger=logger,
  571. base=Undefined
  572. )
  573. .. versionadded:: 2.8
  574. :param logger: the logger to use. If not provided, a default logger
  575. is created.
  576. :param base: the base class to add logging functionality to. This
  577. defaults to :class:`Undefined`.
  578. """
  579. if logger is None:
  580. import logging
  581. logger = logging.getLogger(__name__)
  582. logger.addHandler(logging.StreamHandler(sys.stderr))
  583. if base is None:
  584. base = Undefined
  585. def _log_message(undef):
  586. if undef._undefined_hint is None:
  587. if undef._undefined_obj is missing:
  588. hint = '%s is undefined' % undef._undefined_name
  589. elif not isinstance(undef._undefined_name, string_types):
  590. hint = '%s has no element %s' % (
  591. object_type_repr(undef._undefined_obj),
  592. undef._undefined_name)
  593. else:
  594. hint = '%s has no attribute %s' % (
  595. object_type_repr(undef._undefined_obj),
  596. undef._undefined_name)
  597. else:
  598. hint = undef._undefined_hint
  599. logger.warning('Template variable warning: %s', hint)
  600. class LoggingUndefined(base):
  601. def _fail_with_undefined_error(self, *args, **kwargs):
  602. try:
  603. return base._fail_with_undefined_error(self, *args, **kwargs)
  604. except self._undefined_exception as e:
  605. logger.error('Template variable error: %s', str(e))
  606. raise e
  607. def __str__(self):
  608. rv = base.__str__(self)
  609. _log_message(self)
  610. return rv
  611. def __iter__(self):
  612. rv = base.__iter__(self)
  613. _log_message(self)
  614. return rv
  615. if PY2:
  616. def __nonzero__(self):
  617. rv = base.__nonzero__(self)
  618. _log_message(self)
  619. return rv
  620. def __unicode__(self):
  621. rv = base.__unicode__(self)
  622. _log_message(self)
  623. return rv
  624. else:
  625. def __bool__(self):
  626. rv = base.__bool__(self)
  627. _log_message(self)
  628. return rv
  629. return LoggingUndefined
  630. @implements_to_string
  631. class DebugUndefined(Undefined):
  632. """An undefined that returns the debug info when printed.
  633. >>> foo = DebugUndefined(name='foo')
  634. >>> str(foo)
  635. '{{ foo }}'
  636. >>> not foo
  637. True
  638. >>> foo + 42
  639. Traceback (most recent call last):
  640. ...
  641. jinja2.exceptions.UndefinedError: 'foo' is undefined
  642. """
  643. __slots__ = ()
  644. def __str__(self):
  645. if self._undefined_hint is None:
  646. if self._undefined_obj is missing:
  647. return u'{{ %s }}' % self._undefined_name
  648. return '{{ no such element: %s[%r] }}' % (
  649. object_type_repr(self._undefined_obj),
  650. self._undefined_name
  651. )
  652. return u'{{ undefined value printed: %s }}' % self._undefined_hint
  653. @implements_to_string
  654. class StrictUndefined(Undefined):
  655. """An undefined that barks on print and iteration as well as boolean
  656. tests and all kinds of comparisons. In other words: you can do nothing
  657. with it except checking if it's defined using the `defined` test.
  658. >>> foo = StrictUndefined(name='foo')
  659. >>> str(foo)
  660. Traceback (most recent call last):
  661. ...
  662. jinja2.exceptions.UndefinedError: 'foo' is undefined
  663. >>> not foo
  664. Traceback (most recent call last):
  665. ...
  666. jinja2.exceptions.UndefinedError: 'foo' is undefined
  667. >>> foo + 42
  668. Traceback (most recent call last):
  669. ...
  670. jinja2.exceptions.UndefinedError: 'foo' is undefined
  671. """
  672. __slots__ = ()
  673. __iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \
  674. __ne__ = __bool__ = __hash__ = \
  675. Undefined._fail_with_undefined_error
  676. # remove remaining slots attributes, after the metaclass did the magic they
  677. # are unneeded and irritating as they contain wrong data for the subclasses.
  678. del Undefined.__slots__, DebugUndefined.__slots__, StrictUndefined.__slots__