Flask Routing & Templates
Flask routing and templates are essential components for building dynamic web applications. Routing determines how different URLs are handled by the application, while templates allow developers to generate dynamic HTML pages using Python data.
Flask uses the Jinja2 template engine to render HTML pages with dynamic content.
What is Routing in Flask?
Routing refers to mapping URLs to specific functions in a Flask application. Each route defines which function should run when a user visits a particular URL.
Flask uses the @app.route() decorator to define routes.
In this example, when the root URL (/) is accessed, the home() function runs and returns a message.
Multiple Routes
You can create multiple routes to handle different pages of a website.
Each route corresponds to a specific URL.
Dynamic Routes
Flask allows dynamic URL parameters that can pass values directly to functions.
Visiting /user/Alice will display Hello Alice.
Route Parameters with Data Types
Flask supports specifying data types for route parameters.
Here, the route only accepts integer values.
HTTP Methods in Routes
Flask routes can handle different HTTP methods such as GET and POST.
This allows the route to handle both GET and POST requests.
Introduction to Flask Templates
Templates allow developers to separate application logic from presentation. Flask uses the Jinja2 template engine to render dynamic HTML pages.
Templates are stored inside a folder named templates.
Rendering a Template
This renders the HTML file located in the templates directory.
Example Template File
Create a file named templates/index.html.
This HTML page will be rendered when the route is accessed.
Passing Data to Templates
Flask allows passing variables from Python code to HTML templates.
Inside the template:
The variable name will be replaced with the value passed from Python.
Using Loops in Templates
Jinja2 templates support loops and conditions.
Template file:
This dynamically generates a list of users.
Using Conditions in Templates
This allows conditional rendering inside HTML templates.
Project Structure
flask_app/
│
├── app.py
│
├── templates/
│ ├── index.html
│ └── users.html
│
└── static/
├── css/
└── js/
This structure keeps application logic and frontend files organized.
Best Practices
- Keep routing logic simple and clean.
- Use templates to separate presentation from backend logic.
- Use Jinja2 features for dynamic HTML generation.
- Organize templates in a structured folder.
Conclusion
Flask routing allows developers to map URLs to specific functions, while templates enable dynamic HTML rendering using Python data. Together, they form the foundation for building dynamic web applications with Flask.
Understanding routing and templates is essential for developing scalable Flask applications and REST APIs.
In the next tutorial, we will explore Flask Forms & Request Handling and learn how Flask processes user input from web forms.

