Lesson 2: Routes, Jinja, and Templates
Master Flask routing system, Jinja templating engine, and template organization for building dynamic web applications.
Lesson Objectives
- Learn what a route is and how it connects URLs to functions in Flask
- Understand what Jinja is and how it creates dynamic web pages
- Discover what the templates folder is and how it organizes your HTML files
Watch: Routes, Jinja, and Templates Tutorial
Routes, Jinja, and Templates - Notes
1. Routes File (routes.py)
Location: Inside the app folder.
Purpose: Works like the controller of the system.
Function: Defines what happens when someone visits a specific URL on the website.
Examples:
/→ Root (ex: bryanmarshall.com) → Displays index.html./about→ ex: bryanmarshall.com/about → Displays about.html./animals→ ex: bryanmarshall.com/animals → Displays animals.html.
Tip: If a link doesn't work, it's probably missing a route.
Difference from Blueprints:
- Routes → For simple/basic pages (index, about, animals).
- Blueprints → For more complex features (like database connections).
- Instead of using app, we call the blueprint by its specific name and attach it separately.
- Blueprints let us organize/segment code into logical pieces.
2. Templates Folder
Location: Inside the app folder.
Purpose: Stores all HTML files for the project.
Examples: index.html, about.html, animals.html.
Behavior:
- Files here are usually static HTML (don't change much).
- Can include special Flask/Python code to make them dynamic.
3. Jinja (Template Engine)
Definition: A template language that lets you mix Python/Flask code inside HTML.
Syntax: Uses double curly braces {{ }} for dynamic content.
Example:
<a href="{{ url_for('index') }}">Home</a>This tells Flask to grab the URL for the index route and place it here.
Features:
- Insert dynamic data into HTML.
- Reuse common layouts (e.g., headers, footers).
- Define blocks that can be extended in multiple pages.
Why Important: Allows us to build websites that look consistent across pages and can display changing data.
Key Takeaways
- Routes file (routes.py) = Defines basic web paths and what HTML file to show.
- Blueprints = Advanced version of routes for organizing larger apps.
- Templates folder = Stores HTML files used by routes and blueprints.
- Jinja = Lets us insert Python/Flask code inside HTML using
{{ }}to make pages dynamic.