Flask and Jinja Template Guide
1. Introduction to Flask
What is Flask?
Flask is a lightweight framework in Python used to create web applications. Its simple, flexible, and allows you to build
anything from small projects to big web apps.
Example: Flask helps you create a website that shows user data or manages forms.
Flask vs. Django
Flask is simpler and gives you more control, while Django comes with many features ready-made (like authentication,
admin panel). Flask is good for learning and small projects; Django is better for big, complex apps.
Installing Flask
Install Flask using pip:
pip install flask
2. Setting Up a Flask Project
Project structure
A typical Flask project looks like this:
myproject/
app.py # Main Flask application
templates/ # HTML files (Jinja templates)
static/ # CSS, JavaScript, images
Flask and Jinja Template Guide
Running the Flask server
In your app.py, add this code:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
if __name__ == "__main__":
app.run(debug=True)
Run it:
python app.py
Open http://127.0.0.1:5000 in your browser to see your app.
3. Routing in Flask
Basic routes
A route maps a URL to a function. For example:
Flask and Jinja Template Guide
@app.route("/about")
def about():
return "This is the About page!"
Dynamic routes
You can create routes with variables:
@app.route("/user/<username>")
def user_profile(username):
return f"Hello, {username}!"
URL converters
Restrict the type of variables in routes:
@app.route("/post/<int:post_id>")
def post(post_id):
return f"Post ID: {post_id}"
4. Flask Templates with Jinja
What is Jinja?
Jinja is a templating language that allows you to embed Python code in HTML.
Rendering templates
Example:
Flask and Jinja Template Guide
from flask import render_template
@app.route("/")
def home():
return render_template("home.html")
Template inheritance
Create a base layout:
<!-- base.html -->
<html>
<body>
{% block content %}{% endblock %}
</body>
</html>
Extend it in another file:
<!-- home.html -->
{% extends "base.html" %}
{% block content %}
<h1>Welcome to My Site</h1>
{% endblock %}
Flask and Jinja Template Guide
Template variables
Pass variables to templates:
@app.route("/")
def home():
return render_template("home.html", username="John")
Access it in Jinja:
<p>Hello, {{ username }}</p>