Skip to content

Commit

Permalink
error for render_template outside app context
Browse files Browse the repository at this point in the history
  • Loading branch information
Yourun-proger authored and davidism committed Jul 13, 2022
1 parent 7096b2c commit 58f3536
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
3 changes: 3 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions src/flask/templating.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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)

0 comments on commit 58f3536

Please sign in to comment.