Skip to content
Myr

Fix bug with when using Markup on ChainableUndefined

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Wrapping a ChainableUndefined object with Markup causes an UndefinedError because Markup thinks that ChainableUndefined has an attribute called __html__ and tries to call it. This commit fixes this by defining a method __html__ that calls ChainableUndefined.__str__. We also add a regression test.

authored by Laurence de Bruxelles · committed by David Lord · parent e68d9b8 · Browse files · 2 files+12 added−4 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+12 added−4 removed

  • tests:+5 added−0 removed
  • other:+7 added−4 removed

2 files+12 added−4 removed

modified:jinja2/runtime.py+7 added-4 removed
751 unmodified lines
752# No @implements_to_string decorator here because __str__753# is not overwritten from Undefined in this class.754# This would cause a recursion error in Python 2.755class ChainableUndefined(Undefined):756 """An undefined that is chainable, where both757 __getattr__ and __getitem__ return itself rather than758 raising an :exc:`UndefinedError`:756 """An undefined that is chainable, where both ``__getattr__`` and757 ``__getitem__`` return itself rather than raising an758 :exc:`UndefinedError`.759760 >>> foo = ChainableUndefined(name='foo')761 >>> str(foo.bar['baz'])762 ''
1 unmodified line
764 Traceback (most recent call last):765 ...766 jinja2.exceptions.UndefinedError: 'foo' is undefined767768 .. versionadded:: 2.11768 .. versionadded:: 2.11.0769 """770 __slots__ = ()771772 def __html__(self):773 return self.__str__()774775 def __getattr__(self, _):776 return self777778 __getitem__ = __getattr__
59 unmodified lines
modified:tests/test_regression.py+5 added
541 unmodified lines
542 tmpl = env.from_string('''543 {%- for value in values recursive %}1{% else %}0{% endfor -%}544 ''')545 assert tmpl.render(values=[]) == '0'546547 def test_markup_and_chainable_undefined(self):548 from jinja2 import Markup549 from jinja2.runtime import ChainableUndefined550 assert str(Markup(ChainableUndefined())) == ''