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

diagram Diagram mermaid

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.html
text
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.

Visualize it

Here’s how a view function’s data becomes the final HTML sent to the browser.

diagram Template rendering flow mermaid
How render_template turns data and a template into HTML

🧪 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