In this tutorial, we will learn how to use templates in Flask. We will explore rendering templates using Jinja2, template inheritance, and using template filters and control structures.
First, ensure Flask is installed. If not, install it using:
pip install flask
Create a new Python file, for example, app.py, and import Flask and render_template:
from flask import Flask, render_template app = Flask(__name__)
Flask uses Jinja2 for templating. Create a directory named templates in the same folder as your app.py. Inside the templates directory, create an HTML file called index.html:
Welcome Welcome, {{ name }}!
Now, update app.py to render this template:
@app.route('/') def home(): return render_template('index.html', name='John')
When you visit http://127.0.0.1:5000/, it will render the template and display "Welcome, John!".
Template inheritance allows you to define a base structure and extend it in other templates. Create a new file base.html in the templates directory:
{% block title %}My App{% endblock %} My Application
{% block content %}{% endblock %}
Now, create a file home.html to extend base.html:
{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %}Welcome to the Home Page
This is the main content of the home page.
{% endblock %}
Update app.py to render home.html:
@app.route('/') def home(): return render_template('home.html')
Jinja2 provides filters and control structures for dynamic content. Update home.html to include these examples:
{% block content %}Welcome to the Home Page
{{ 'This text is uppercase' | upper }}
{{ 12345 | striptags }}
Logged in as {{ user }}
{% else %}Not logged in
{% endif %} {% endblock %}Update app.py to pass dynamic data:
@app.route('/') def home(): return render_template('home.html', user='John')
When you visit the page, it will display the filters and conditional content based on the dynamic data.
Run your Flask application:
python app.py
Navigate to http://127.0.0.1:5000 to see the rendered templates in action.
In this tutorial, we learned about Flask templates, including rendering templates with Jinja2, using template inheritance, and applying filters and control structures. These techniques enable you to create dynamic and reusable templates for your Flask applications.