From 967907ee81cbc671cd8982bdc02a9d3335fdde11 Mon Sep 17 00:00:00 2001 From: Alexander Pantyukhin Date: Tue, 24 Mar 2015 12:20:28 +0000 Subject: [PATCH] before_render_template signal can override render template. --- flask/templating.py | 15 +++++++++++++-- tests/test_signals.py | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/flask/templating.py b/flask/templating.py index 74ff104f..d76d82a0 100644 --- a/flask/templating.py +++ b/flask/templating.py @@ -101,8 +101,19 @@ class DispatchingJinjaLoader(BaseLoader): def _render(template, context, app): - """Renders the template and fires the signal""" - before_render_template.send(app, template=template, context=context) + """Renders the template and fires signals. + + 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) template_rendered.send(app, template=template, context=context) return rv diff --git a/tests/test_signals.py b/tests/test_signals.py index bab5b155..f77e645f 100644 --- a/tests/test_signals.py +++ b/tests/test_signals.py @@ -67,6 +67,22 @@ def test_before_render_template(): assert context['whiskey'] == 43 assert rv.data == b'

43

' +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(): app = flask.Flask(__name__)