In this Flask Tutorial we are going to learn about Flask Template Inheritance, in the previous lesson we have learned that how you can create templates in Flask, now it is time to talk about template inheritance in flask. as we have created three html files in our previous lesson, but the problem is this that we are duplicating our code in the html files, for example in three html files we have header, body and html tags, so we need to remove this duplication from our templates, by this reason we are using Template Inheritance in Flask, by using Flask Template inheritance we are avoiding code duplication in our templates, so now let’s start our coding.
We are not going to bring changes in our app.py file, and this is the app.py file.
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 30 |
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') @app.route('/contact') def Contact(): return render_template('contact.html') @app.route('/about') def About(): return render_template('about.html') #run flask app if __name__ == "__main__": app.run(debug=True) |
We need to create a new html file at name base.html file, this will be a base template for all of our html files, and our all html files will extends from this base.html file, in our base.html, you can see that we have created some blocks for our title and also body, now you can change this block in your other html files. you can create as much blocks as you want according to your requirements.
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> {% block body %} {% endblock %} </body> </html> |
And in here we have created our index.html file, the first thing you need to extends from the base.html, and after that you need to create the same block names as we have created in our base.html.
templates/index.html
1 2 3 4 5 6 7 8 9 10 11 |
{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block body %} <h1>Home Page - Template Inheritance</h1> {% endblock %} |
templates/contact.html
1 2 3 4 5 6 7 8 9 10 11 |
{% extends 'base.html' %} {% block title %}Contact{% endblock %} {% block body %} <h1>Contact Page - Template Inheritance</h1> {% endblock %} |
templates/about.html
1 2 3 4 5 6 7 8 9 10 11 |
{% extends 'base.html' %} {% block title %}About{% endblock %} {% block body %} <h1>About Page - Template Inheritance</h1> {% endblock %} |
Run your Flask application and go to http://localhost:5000/, this is the result.