Merge pull request #4693 from Yourun-proger/msg_app_ctx

error message for `render_template` outside app context
This commit is contained in:
David Lord 2022-07-13 13:50:05 -07:00 committed by GitHub
commit a7859c6947
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 0 deletions

View file

@ -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

View file

@ -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)