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.html files and only pass data from Python.
The basic flow
false
flowchart LR R[Request] --> V[Flask View Function] V -->|context dict| T[Jinja2 Template] T --> H[Rendered HTML] H --> Resp[Response]
false
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
By convention:
templates/templates/folder next to your app/package
Example:
myapp/
app.py
templates/
home.htmlmyapp/
app.py
templates/
home.htmlFlask will look for templates in that templates/templates/ folder automatically.
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.
π§ͺ Try It Yourself
Exercise 1 β Create a Flask App
Exercise 2 β Dynamic Route
Exercise 3 β Return JSON
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
