- if
- endif
Flask Jinja template with conditional
examples/flask/jinja-conditional/app.py
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)
examples/flask/jinja-conditional/templates/echo.html
<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 %}
examples/flask/jinja-conditional/test_app.py
import app def test_app(): web = app.app.test_client() rv = web.get('/') assert rv.status == '200 OK' assert b'<form action="/echo" method="POST">' in rv.data 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 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