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
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
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:
text
myapp/
app.py
templates/
home.htmltext
myapp/
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.
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
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
