Skip to content

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.html
myapp/
  app.py
  templates/
    home.html

Flask 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 coffee

Was this page helpful?

Let us know how we did