forked from orbit-oss/flask
before_render_template signal can override render template.
This commit is contained in:
parent
1fbeb337c4
commit
967907ee81
2 changed files with 29 additions and 2 deletions
|
|
@ -101,8 +101,19 @@ class DispatchingJinjaLoader(BaseLoader):
|
||||||
|
|
||||||
|
|
||||||
def _render(template, context, app):
|
def _render(template, context, app):
|
||||||
"""Renders the template and fires the signal"""
|
"""Renders the template and fires signals.
|
||||||
before_render_template.send(app, template=template, context=context)
|
|
||||||
|
It is possible to override render template in the before_render_template signal.
|
||||||
|
It can be done only if exactly one receiver and it return not None result."""
|
||||||
|
|
||||||
|
brt_resp = before_render_template.send(app, template=template, context=context)
|
||||||
|
|
||||||
|
if len(brt_resp) == 1:
|
||||||
|
first_resp = brt_resp[0]
|
||||||
|
|
||||||
|
if len(first_resp) == 2 and first_resp[1] is not None:
|
||||||
|
return first_resp[1]
|
||||||
|
|
||||||
rv = template.render(context)
|
rv = template.render(context)
|
||||||
template_rendered.send(app, template=template, context=context)
|
template_rendered.send(app, template=template, context=context)
|
||||||
return rv
|
return rv
|
||||||
|
|
|
||||||
|
|
@ -67,6 +67,22 @@ def test_before_render_template():
|
||||||
assert context['whiskey'] == 43
|
assert context['whiskey'] == 43
|
||||||
assert rv.data == b'<h1>43</h1>'
|
assert rv.data == b'<h1>43</h1>'
|
||||||
|
|
||||||
|
def test_before_render_template_signal_not_None_result_render_skip_render_template():
|
||||||
|
app = flask.Flask(__name__)
|
||||||
|
|
||||||
|
@app.route('/')
|
||||||
|
def index():
|
||||||
|
return flask.render_template('simple_template.html', whiskey=42)
|
||||||
|
|
||||||
|
recorded = []
|
||||||
|
|
||||||
|
def record(sender, template, context):
|
||||||
|
recorded.append((template, context))
|
||||||
|
return 'Not template string'
|
||||||
|
|
||||||
|
with flask.before_render_template.connected_to(record):
|
||||||
|
rv = app.test_client().get('/')
|
||||||
|
assert rv.data == 'Not template string'
|
||||||
|
|
||||||
def test_request_signals():
|
def test_request_signals():
|
||||||
app = flask.Flask(__name__)
|
app = flask.Flask(__name__)
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue