In this section, we will explore how to render templates using Jinja2 in Flask. Templates allow you to separate the presentation layer from the business logic, making your code cleaner and more maintainable.
What is Jinja2?
Jinja2 is a modern and designer-friendly templating engine for Python. It is used to render HTML templates in Flask applications. Jinja2 allows you to:
- Embed Python-like expressions in your HTML.
- Use control structures like loops and conditionals.
- Create reusable components with template inheritance.
Setting Up Templates in Flask
Directory Structure
Flask looks for templates in a folder named templates
in the root directory of your application. Here is an example directory structure:
my_flask_app/ │ ├── app.py ├── templates/ │ ├── base.html │ ├── index.html │ └── about.html └── static/ ├── css/ ├── js/ └── images/
Creating a Basic Template
Let's create a simple HTML template named index.html
:
<!-- templates/index.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> <h1>Welcome to {{ title }}</h1> <p>{{ description }}</p> </body> </html>
Rendering the Template in Flask
To render the index.html
template, you use the render_template
function provided by Flask. Here is an example of how to do this in your app.py
:
# app.py from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html', title='My Flask App', description='This is a simple Flask application.') if __name__ == '__main__': app.run(debug=True)
In this example:
- The
render_template
function takes the name of the template file and any variables you want to pass to the template. - The variables
title
anddescription
are passed to theindex.html
template and rendered in the appropriate places.
Template Inheritance
Template inheritance allows you to create a base template that other templates can extend. This is useful for maintaining a consistent layout across multiple pages.
Creating a Base Template
Create a base template named base.html
:
<!-- templates/base.html --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}My Flask App{% endblock %}</title> </head> <body> <header> <h1>My Flask App</h1> </header> <main> {% block content %}{% endblock %} </main> <footer> <p>© 2023 My Flask App</p> </footer> </body> </html>
Extending the Base Template
Now, modify the index.html
to extend the base.html
template:
<!-- templates/index.html --> {% extends "base.html" %} {% block title %}Home - My Flask App{% endblock %} {% block content %} <h2>Welcome to {{ title }}</h2> <p>{{ description }}</p> {% endblock %}
In this example:
- The
{% extends "base.html" %}
statement tells Jinja2 to usebase.html
as the base template. - The
{% block title %}
and{% block content %}
tags define the content that will be inserted into the corresponding blocks in the base template.
Practical Exercise
Task
- Create a new template named
about.html
that extendsbase.html
. - Add a title block with the text "About - My Flask App".
- Add a content block with a heading and a paragraph describing your application.
Solution
<!-- templates/about.html --> {% extends "base.html" %} {% block title %}About - My Flask App{% endblock %} {% block content %} <h2>About My Flask App</h2> <p>This application is built using Flask, a lightweight web framework for Python.</p> {% endblock %}
Adding a Route for the About Page
Update your app.py
to include a route for the about page:
# app.py from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html', title='My Flask App', description='This is a simple Flask application.') @app.route('/about') def about(): return render_template('about.html') if __name__ == '__main__': app.run(debug=True)
Summary
In this section, you learned how to:
- Set up and render templates using Jinja2 in Flask.
- Use template inheritance to create reusable components.
- Pass variables from your Flask application to your templates.
Next, we will explore how to work with static files in Flask.
Flask Web Development Course
Module 1: Introduction to Flask
- What is Flask?
- Setting Up Your Development Environment
- Creating Your First Flask Application
- Understanding Flask Application Structure
Module 2: Basic Flask Concepts
- Routing and URL Mapping
- Handling HTTP Methods
- Rendering Templates with Jinja2
- Working with Static Files
Module 3: Forms and User Input
Module 4: Database Integration
- Introduction to Flask-SQLAlchemy
- Defining Models
- Performing CRUD Operations
- Database Migrations with Flask-Migrate
Module 5: User Authentication
Module 6: Advanced Flask Concepts
Module 7: RESTful APIs with Flask
Module 8: Deployment and Production
- Configuring Flask for Production
- Deploying to Heroku
- Deploying to AWS
- Monitoring and Performance Tuning