Templates, Forms & Static Files
Build HTML pages with Jinja templates (variables, loops, conditions, inheritance), link pages with url_for, serve CSS and images, handle forms with GET and POST, validate input, show flash messages, and protect forms against XSS and CSRF attacks.
Jinja templates
Writing HTML inside Python strings gets messy fast. Instead, put HTML in templates in a templates/ folder and fill in the changing parts with Jinja, Flask's template language:
{{ patient.name }}inserts a value. Jinja escapes it automatically, so<script>typed by a user shows as text instead of running.{% for p in patients %} … {% endfor %}loops;{% if p.overdue %} … {% endif %}decides.- Filters change values:
{{ name|upper }},{{ price|round(2) }}. - Inheritance: a
base.htmlholds the shared layout with{% block content %}{% endblock %}; each page says{% extends "base.html" %}and fills in the block.
In the view, return render_template("patients.html", patients=rows) renders the template with your data.
Try it: render a template
Edit the data and see the HTML Jinja produces. Then switch off autoescaping to see why it matters.
Interactive: this part runs in your browser.
Forms: GET shows, POST submits
A typical form view handles two methods: GET shows the empty form; POST receives the submitted data, validates it, saves it, and redirects (so refreshing the page does not submit twice: the "Post/Redirect/Get" pattern). flash() stores a one-time message ("Appointment booked") to show on the next page.
from flask import Flask, render_template, request, redirect, url_for, flash
app = Flask(__name__)
app.config["SECRET_KEY"] = "change-me" # needed for flash messages; load from an env variable in real apps
bookings = []
@app.route("/book", methods=["GET", "POST"])
def book():
errors = {}
if request.method == "POST":
name = request.form.get("name", "").strip()
day = request.form.get("day", "")
if not name:
errors["name"] = "Please enter your name."
if day not in {"Mon", "Tue", "Wed", "Thu", "Fri"}:
errors["day"] = "Choose a weekday."
if not errors:
bookings.append({"name": name, "day": day})
flash(f"Booked {name} on {day}.")
return redirect(url_for("book")) # Post/Redirect/Get
return render_template("book.html", errors=errors, bookings=bookings){% extends "base.html" %}
{% block content %}
{% for msg in get_flashed_messages() %}<p class="flash">{{ msg }}</p>{% endfor %}
<form method="post">
<label>Name <input name="name"></label> {{ errors.name }}
<label>Day
<select name="day">{% for d in ["Mon", "Tue", "Wed", "Thu", "Fri"] %}<option>{{ d }}</option>{% endfor %}</select>
</label> {{ errors.day }}
<button>Book</button>
</form>
<ul>{% for b in bookings %}<li>{{ b.name }}: {{ b.day }}</li>{% endfor %}</ul>
{% endblock %}Static files and url_for
CSS, JavaScript and images go in a static/ folder. Link to them, and to your own pages, with url_for instead of typing paths: {{ url_for('static', filename='style.css') }} and {{ url_for('book') }}. If you later change a URL, every link updates.
Two attacks every form must handle
- XSS (cross-site scripting): an attacker submits text containing
<script>, and your page shows it to other users, running their code in their browsers. Jinja's autoescaping prevents it; never mark user input as|safe. - CSRF (cross-site request forgery): another website tricks a logged-in user's browser into submitting your form. Defend with a secret CSRF token in every form; the Flask-WTF extension adds it automatically, along with form validation helpers.
And always validate on the server: checks in the browser are only for convenience, because anyone can send any request directly.
Quiz
1. What does {% extends "base.html" %} do?
2. A user enters <script>alert(1)</script> as their name. With Jinja's default autoescaping, the page…
3. Why redirect after a successful POST?
4. Is checking a form field with JavaScript in the browser enough?
📚 Further reading
Trusted, mostly free sources: official documentation, well-known textbooks and courses. When you want to confirm or go deeper on anything here, start with these.
- Jinja template designer documentation ↗ every template feature
- Flask tutorial: the Flaskr blog app ↗ the official step-by-step tutorial with an app factory, blueprints and tests