Multiple issues when using `StrictUndefined` in app.jinja_env.undefined
ddorian opened this issue · 2 comments
ddorian commented
I like to use StrictUndefined to catch more errors in my templates. This raises many errors in flask-admin. You can simply check by enabling it in tests.
from jinja2 import StrictUndefined
app.jinja_env.undefined = StrictUndefined
Environment:
- Python version:3.12
- Flask version:3.0.3
- Flask-Admin version:2.0.0a0
For now I'm using a custom class to ignore these (I configure all flask-admin blueprints to start with admin2
):
class MyStrictUndefined(StrictUndefined):
"""Work like StrictUndefined except in flask-admin views/blueprints."""
@property
def is_admin2_blp(self) -> bool:
if flask.request and flask.request.blueprint:
return bool(flask.request.blueprint.startswith("admin2"))
return False
def __eq__(self, other: t.Any) -> bool: # type: ignore[override]
if self.is_admin2_blp:
return type(self) is type(other)
self._fail_with_undefined_error()
def __ne__(self, other: t.Any) -> bool: # type: ignore[override]
if self.is_admin2_blp:
return not self.__eq__(other)
self._fail_with_undefined_error()
#
# def __hash__(self) -> int:
# return id(type(self))
#
# def __str__(self) -> str:
# return ""
#
# def __len__(self) -> int:
# return 0
#
# def __iter__(self) -> t.Iterator[t.Any]:
# yield from ()
#
# async def __aiter__(self) -> t.AsyncIterator[t.Any]:
# for _ in ():
# yield
def __bool__(self) -> bool: # type: ignore[override]
if self.is_admin2_blp:
return False
self._fail_with_undefined_error()
# def __repr__(self) -> str:
# return "Undefined"
samuelhwilliams commented
Agree this would be nice to fix - would be very happy to accept a PR on this 🙏