How to Create Templates in Flask

Flask is a lightweight and flexible web framework for Python, perfect for building web applications quickly and cleanly. One of its core strengths lies in its use of templates to separate HTML from Python logic, making your code more modular and maintainable.

In this post, we’ll cover how to create and use templates in Flask using Jinja2, Flask’s default templating engine.

Project Structure

Before diving in, here’s a typical minimal structure of a Flask project that uses templates:

my_flask_app/

├── app.py
└── templates/
    ├── base.html
    └── index.html

Flask automatically looks for a templates/ directory to load HTML templates.

Step 1: Install Flask

If you haven’t already, install Flask using pip:

pip install Flask

Step 2: Create a Basic Flask App

Create a file called app.py and add the following:

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)

Here, render_template tells Flask to look inside the templates/ folder and load index.html.

Step 3: Create Your First Template

Inside a new templates/ folder, create a file called index.html:

<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Home Page</title>
</head>
<body>
    <h1>Hello from Flask!</h1>
</body>
</html>

Start your app by running:

python app.py

Visit http://localhost:5000/ in your browser, and you’ll see your template rendered.

Step 4: Using Template Inheritance

Flask with Jinja2 supports template inheritance, which helps avoid repeating HTML boilerplate.

Create a base template:

<!-- templates/base.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    <header>
        <h1>Welcome to My Site</h1>
    </header>

    <main>
        {% block content %}{% endblock %}
    </main>
</body>
</html>

Now modify index.html to extend it:

<!-- templates/index.html -->
{% extends "base.html" %}

{% block title %}Home{% endblock %}

{% block content %}
    <p>This is the home page content.</p>
{% endblock %}

Step 5: Passing Data to Templates

You can pass variables from Flask to your template:

@app.route('/')
def home():
    return render_template('index.html', name='Matthew')

Then in your index.html:

{% block content %}
    <p>Hello, {{ name }}!</p>
{% endblock %}

This will output: Hello, Matthew!

Bonus Tips

Use {% for %} and {% if %} to add logic in templates:

<ul>
  {% for item in items %}
      <li>{{ item }}</li>
  {% endfor %}
</ul>

Escape variables for safety: {{ variable }} auto-escapes to prevent XSS.
Include partials using {% include 'filename.html' %} for components like navbars or footers.

Conclusion

Templates are an essential part of any Flask application. Using Jinja2, you can create clean, maintainable HTML views that integrate tightly with your Python logic. With template inheritance and dynamic variable injection, Flask gives you the flexibility to scale your application’s front end efficiently.

Leave a Reply

Your email address will not be published. Required fields are marked *