Contents
Rendering Templates in Flask
Rendering templates is a powerful feature in Flask that allows you to create dynamic web pages by combining Python code with HTML. Flask uses the Jinja2 template engine to make this possible. Let’s dive into how you can create and render HTML templates, use template inheritance, and pass data from your Flask views to these templates.
Introduction to Jinja2 Template Engine
Jinja2 is the template engine that Flask uses to combine Python code with HTML. It allows you to write Python-like expressions inside your HTML files, making your web pages dynamic and responsive to data.
Here’s a quick example of what a Jinja2 template might look like:
{{ title }}
Hello, {{ name }}!
In this template:
{{ title }}
and{{ name }}
are placeholders for variables that you can pass from your Flask app.- Jinja2 will replace these placeholders with the actual values when rendering the template.
Creating and Rendering HTML Templates with Flask
To use templates in Flask, you need to create an HTML file and place it in a templates
directory within your project. Let’s create a simple example.
Step 1: Set Up the Template Directory
In your project directory, create a templates
folder. Inside this folder, create an HTML file called index.html
:
/your-project
/templates
index.html
app.py
Step 2: Create a Basic Template
Here’s what your index.html
might look like:
{{ title }}
Welcome to {{ name }}'s Website
This is a basic Flask template rendering example.
Step 3: Render the Template in Flask
Now, you can render this template from your Flask view function in app.py
:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html', title='Home Page', name='John Doe')
if __name__ == '__main__':
app.run(debug=True)
In this example:
render_template('index.html', title='Home Page', name='John Doe')
tells Flask to renderindex.html
and replace{{ title }}
with “Home Page” and{{ name }}
with “John Doe”.- When you visit
http://127.0.0.1:5000/
, you’ll see your dynamic HTML page with the data you passed in.
Using Template Inheritance (Base Templates)
Template inheritance allows you to create a base template that other templates can extend. This is useful for maintaining consistency across multiple pages in your application.
Step 1: Create a Base Template
In your templates
directory, create a new file called base.html
:
{% block title %}My Flask App{% endblock %}
My Flask Application
{% block content %}{% endblock %}
In this base template:
{% block title %}{% endblock %}
and{% block content %}{% endblock %}
are placeholders that can be overridden by other templates.
Step 2: Create a Child Template
Now, create another template called home.html
that extends base.html
:
{% extends 'base.html' %}
{% block title %}Home{% endblock %}
{% block content %}
Welcome to the Home Page!
This is the home page of our Flask app.
{% endblock %}
Step 3: Render the Child Template in Flask
Modify your view function to render home.html
:
@app.route('/')
def home():
return render_template('home.html')
When you visit the homepage, Flask will use base.html
as the layout and insert the content from home.html
into the appropriate blocks.
Passing Data from Flask Views to Templates
You can pass data from your Flask view functions to your templates using the render_template
function. This data can then be accessed within your templates using Jinja2 syntax.
Example:
@app.route('/profile/')
def profile(username):
user_info = {
'name': username,
'age': 30,
'location': 'New York'
}
return render_template('profile.html', user=user_info)
In the profile.html
template, you can access the user
dictionary:
{% extends 'base.html' %}
{% block title %}{{ user.name }}'s Profile{% endblock %}
{% block content %}
{{ user.name }}
Age: {{ user.age }}
Location: {{ user.location }}
{% endblock %}
This will dynamically render a user’s profile page based on the data passed from the view function.
Summary
Rendering templates with Flask allows you to create dynamic, data-driven web pages. The Jinja2 template engine makes it easy to embed Python logic within your HTML, while template inheritance helps maintain a consistent layout across your application. By passing data from your Flask views to templates, you can create personalized and interactive user experiences.
Related Chapters
- What is Flask?
- Setting Up the Development Environment
- Your First Flask Application
- Understanding Flask Routing
- Rendering Templates
- Working with Forms
- Working with Databases
- User Authentication
- File Uploads and Handling
- RESTful APIs with Flask
- Application Configuration and Deployment
- Testing in Flask
- Flask Extensions
- Handling Error Pages
- Planning the Project
- Developing the Backend with Flask
- Developing the Frontend
- Deployment and Scaling