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 include

$ tree
.
├── jinja_include.py
├── templates
│   ├── echo.html
│   ├── incl
│   │   └── echo_form.html
│   └── main.html
└── test_jinja_include.py
from flask import Flask, request, render_template
app = Flask(__name__)

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

@app.route("/echo", methods=['POST'])
def echo():
    user_text = request.form.get('text', '')
    return render_template('echo.html', text=user_text)
<h1>Main</h1>

{% include 'incl/echo_form.html' %}

{% include 'incl/echo_form.html' %}

{% if text %}
  You said: <b>{{ text }}</b>
{% else %}
  You did not say anything.
{% endif %}
<form action="/echo" method="POST">
<input name="text">
<input type="submit" value="Echo">
</form>

import jinja_include
import pytest

@pytest.fixture()
def web():
    return jinja_include.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

    assert b'You did not say anything.' not in rv.data
    assert b'You said: <b>foo bar</b>' not in rv.data

def test_echo_post_param(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_post_empty_param(web):
    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):
    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