Introduction to Jinja2
A template engine turns a template file (HTML + placeholders) into a final HTML string.
Instead of writing:
- long HTML strings inside Python
You place HTML in .html files and only pass data from Python.
The basic flow
Section titled “The basic flow”flowchart LR R[Request] --> V[Flask View Function] V -->|context dict| T[Jinja2 Template] T --> H[Rendered HTML] H --> Resp[Response]
Why templates are important
Section titled “Why templates are important”Templates help you:
- separate presentation (HTML/CSS) from logic (Python)
- reuse layouts (header/footer navigation)
- keep code review simple (HTML changes don’t touch Python)
Where templates live
Section titled “Where templates live”By convention:
templates/folder next to your app/package
Example:
myapp/
app.py
templates/
home.htmlFlask will look for templates in that templates/ folder automatically.
Security note
Section titled “Security note”Jinja2 auto-escapes variables in HTML templates by default (helps prevent XSS).
You should still treat user input as untrusted and validate on the backend.
Visualize it
Section titled “Visualize it”Here’s how a view function’s data becomes the final HTML sent to the browser.
flowchart LR
V["render_template('page.html', data)"] --> L["Jinja2 loads template"]
L --> F["Fills variables and loops"]
F --> H["Final HTML"]
H --> R["Returned to browser"]
🧪 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