Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flask Jinja template with conditional

  • if
  • else
  • endif

In order to show the correct message, we use an if-else-endif construct.

This works fine on the /echo page, but unfortunately the message also shows up on the main page.

How could we avoid that? We could create a new template for the main page where we don’t have this message, but then we will need to duplicate the form. Or we can separate it into another template and include it in both templates.

from flask import Flask, request, render_template
app = Flask(__name__)

@app.route("/")
def main():
    return render_template('echo.html')

@app.route("/echo", methods=['POST'])
def echo():
    user_text = request.form.get('text', '')
    return render_template('echo.html', text=user_text)
<form action="/echo" method="POST">
<input name="text">
<input type="submit" value="Echo">
</form>


{% if text %}
  You said: <b>{{ text }}</b>
{% else %}
  You did not say anything.
{% endif %}
import jinja_conditional

def test_main_page():
    web = jinja_conditional.app.test_client()

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert b'<form action="/echo" method="POST">' in rv.data

    # This is not nice, but this is how it works now.
    assert b'You did not say anything.' in rv.data

def test_echo_post_param():
    web = jinja_conditional.app.test_client()

    rv = web.post('/echo', data={ 'text': 'foo bar' })
    assert rv.status == '200 OK'
    assert b'<form action="/echo" method="POST">' in rv.data
    assert b'You said: <b>foo bar</b>' in rv.data

def test_echo_post_empty_param():
    web = jinja_conditional.app.test_client()

    rv = web.post('/echo', data={ 'text': '' })
    assert rv.status == '200 OK'
    assert b'<form action="/echo" method="POST">' in rv.data
    assert b'You said' not in rv.data
    assert b'You did not say anything.' in rv.data

def test_echo_post_no_param():
    web = jinja_conditional.app.test_client()

    rv = web.post('/echo')
    assert rv.status == '200 OK'
    assert b'<form action="/echo" method="POST">' in rv.data
    assert b'You said' not in rv.data
    assert b'You did not say anything.' in rv.data