In this Flask CRUD Application lesson we are going to learn about Flask CRUD Application Header Design, we want to design our application header, also in this lesson you will be familiar with template inheritance in Flask.
So now open your templates folder and create another HTML file at name of base.html, and this will be our main HTML file that all other files will extends from this file, you can see that in this file we have created some blocks.
tempaltes/base.html
1 2 3 4 5 6 7 8 9 10 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> <h1>{% block body %}{% endblock %}</h1> </body> </html> |
Now let’s bring changes to our index.html. you can see at the top we have extended from our file from base.html file, because in here we are using template inheritance.
templates/index.html
1 2 3 4 5 6 7 8 9 10 11 |
{% extends 'base.html' %} {% block title %}Flask CRUD Application {% endblock %} {% block body %} <h1>Flask CRUD Application - Template Inheritance</h1> {% endblock %} |
If you run your Flask Application you will see the same result.
We want to add our Bootstrap CDN links in our base.html file, so open the file and bring some changes like this.
templates/base.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <meta charset="UTF-8"> <title>{% block title %} {% endblock %} </title> </head> <body> {% block body %} {% endblock %} <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"> </script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"> </script> </body> </html> |
Create another HTML file at name of header.html.
templates/header.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
{% extends 'base.html' %} {% block title %} Flask CRUD {% endblock %} {% block body %} <div class="jumbotron p-3"> <div class="well text-center"> <h1>Flask CRUD Application - Geekscoders.com</h1> </div> </div> {% endblock %} |
Now include your header file in your index file.
templates/index.html
1 2 3 4 5 6 7 8 9 10 11 12 |
{% extends 'base.html' %} {% include 'header.html' %} {% block title %}Flask CRUD Application {% endblock %} {% block body %} <h1>Flask CRUD Application - Template Inheritance</h1> {% endblock %} |
This is our App.py file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
from flask import Flask, render_template #create the object of Flask app = Flask(__name__) #creating our routes @app.route('/') def Index(): return render_template("index.html") #run flask app if __name__ == "__main__": app.run(debug=True) |
Run your application and go to http://localhost:5000/, this will be the result.