diff --git a/CHANGES.rst b/CHANGES.rst index d423aba9..dd4d2b62 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -10,6 +10,9 @@ Unreleased - Relax type annotation for ``after_request`` functions. :issue:`4600` - ``instance_path`` for namespace packages uses the path closest to the imported submodule. :issue:`4600` +- Clearer error message when ``render_template`` and + ``render_template_string`` are used outside an application context. + :pr:`4693` Version 2.1.2 diff --git a/src/flask/templating.py b/src/flask/templating.py index b39adb77..507615c5 100644 --- a/src/flask/templating.py +++ b/src/flask/templating.py @@ -144,6 +144,12 @@ def render_template( context of the template. """ ctx = _app_ctx_stack.top + + if ctx is None: + raise RuntimeError( + "This function can only be used when an application context is active." + ) + ctx.app.update_template_context(context) return _render( ctx.app.jinja_env.get_or_select_template(template_name_or_list), @@ -162,5 +168,11 @@ def render_template_string(source: str, **context: t.Any) -> str: context of the template. """ ctx = _app_ctx_stack.top + + if ctx is None: + raise RuntimeError( + "This function can only be used when an application context is active." + ) + ctx.app.update_template_context(context) return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)