Rendering Templates
Flask renders templates using render_template().
flowchart TD
A["view returns render_template('page.html', user=u)"] --> B["Jinja loads templates/page.html"]
B --> C{"does the name end in .html/.htm/.xml/.xhtml/.svg?"}
C -->|yes| D["autoescape ON"]
C -->|no| E["autoescape OFF"]
D --> F["{{ user.name }} is HTML-escaped"]
E --> G["{{ user.name }} is inserted raw"]
F --> H["string returned to Flask"]
G --> H
H --> I["wrapped in a Response, 200, text/html"]
Step 1: create a template file
Section titled “Step 1: create a template file”Create templates/home.html:
<!doctype html>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>Welcome to Flask</h1>
</body>
</html>Step 2: render it from a route
Section titled “Step 2: render it from a route”from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("home.html")Flask will:
- find
templates/home.html - render it (no variables yet)
- return the HTML as an HTTP response
How template lookup works
Section titled “How template lookup works”Flask searches the templates folder relative to your app.
If you see:
TemplateNotFound: home.html
It usually means:
- your templates folder is missing or incorrectly placed
- your working directory is wrong
- you’re using a package layout and need to confirm the path
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading