Skip to content

Commit a7859c6

Browse files
authored
Merge pull request #4693 from Yourun-proger/msg_app_ctx
error message for `render_template` outside app context
2 parents 7096b2c + 58f3536 commit a7859c6

File tree

2 files changed

+15
-0
lines changed

2 files changed

+15
-0
lines changed

CHANGES.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ Unreleased
1010
- Relax type annotation for ``after_request`` functions. :issue:`4600`
1111
- ``instance_path`` for namespace packages uses the path closest to
1212
the imported submodule. :issue:`4600`
13+
- Clearer error message when ``render_template`` and
14+
``render_template_string`` are used outside an application context.
15+
:pr:`4693`
1316

1417

1518
Version 2.1.2

src/flask/templating.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,12 @@ def render_template(
144144
context of the template.
145145
"""
146146
ctx = _app_ctx_stack.top
147+
148+
if ctx is None:
149+
raise RuntimeError(
150+
"This function can only be used when an application context is active."
151+
)
152+
147153
ctx.app.update_template_context(context)
148154
return _render(
149155
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:
162168
context of the template.
163169
"""
164170
ctx = _app_ctx_stack.top
171+
172+
if ctx is None:
173+
raise RuntimeError(
174+
"This function can only be used when an application context is active."
175+
)
176+
165177
ctx.app.update_template_context(context)
166178
return _render(ctx.app.jinja_env.from_string(source), context, ctx.app)

0 commit comments

Comments
 (0)