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 files and only pass data from Python.

diagram Diagram mermaid

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)

By convention:

  • templates/ folder next to your app/package

Example:

text
myapp/
  app.py
  templates/
    home.html

Flask will look for templates in that templates/ folder automatically.

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.

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

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading