pip install flask
Now, create a new project folder:
mkdir flask_templates
cd flask_templates
Create a Python file app.py
and add the following code:
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def home():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
Inside your project folder, create a templates
directory and add an index.html
file
<!DOCTYPE html>
<html>
<head>
<title>Flask Templates</title>
</head>
<body>
<h1>Welcome to Flask Templates with Jinja2</h1>
</body>
</html>
Modify app.py
to pass a variable:
@app.route("/user/<name>")
def user(name):
return render_template("user.html", username=name)
Now, create a user.html
file inside the templates
folder:
<!DOCTYPE html>
<html>
<head>
<title>User Page</title>
</head>
<body>
<h1>Hello, {{ username }}!</h1>
</body>
</html>
Visit http://127.0.0.1:5000/user/Zia, and it will display:
Hello, Zia!
Modify user.html
to use an if statement:
{% if username == "Admin" %}
<h1>Welcome, Admin!</h1>
{% else %}
<h1>Hello, {{ username }}!</h1>
{% endif %}
Modify app.py
to pass a list of users:
@app.route("/users")
def users():
user_list = ["Alice", "Bob", "Charlie"]
return render_template("users.html", users=user_list)
Now, create a users.html
file:
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>List of Users:</h1>
<ul>
{% for user in users %}
<li>{{ user }}</li>
{% endfor %}
</ul>
</body>
</html>
Visit http://127.0.0.1:5000/users, and you'll see:
List of Users:
- Alice
- Bob
- Charlie
Create base.html
inside templates/
:
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}Flask App{% endblock %}</title>
</head>
<body>
<header>
<h1>Welcome to My Flask App</h1>
</header>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
Now, modify index.html
to extend it
{% extends "base.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h2>This is the Home Page</h2>
{% endblock %}
In this guide, you’ve learned how to:
✅ Use Jinja2 templates in Flask
✅ Pass variables from Flask to templates
✅ Use if conditions and loops in Jinja2
✅ Implement template inheritance for reusable layouts
By mastering Flask templates, you can build dynamic and scalable web applications efficiently! 🚀