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 parameters

In this example there is a single variable in the the template {{ text }} that will be replaced by the value passed to the render_template function.

This happens in the echo function, but not in the main_page function. There we don’t pass the parameter - as we don’t have any value for it.

That’s fine with Jinja, it will put an empty string there, however it will still show the text You said:.

We’ll fix that next.

<form action="/echo" method="POST">
<input name="text">
<input type="submit" value="Echo">
</form>

You said: <b>{{ text }}</b>
from flask import Flask, request, render_template
app = Flask(__name__)

@app.get("/")
def main_page():
    return render_template('echo.html')

@app.post("/echo")
def echo():
    user_text = request.form.get('text', '')
    return render_template('echo.html', text=user_text)
import jinja_parameters
import pytest

@pytest.fixture()
def web():
    return jinja_parameters.app.test_client()


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

def test_echo_data(web):
    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(web):
    rv = web.post('/echo')
    assert rv.status == '200 OK'
    assert b'<form action="/echo" method="POST">' in rv.data
    assert b'You said: <b></b>' in rv.data