Flask Tutorial – Template Inheritance in Flask

In this Flask Tutorial we are going to talk about Template Inheritance in Flask,

so if you have read my previous article, we have talked about using templates in flask,

if you are interested you can check this link,  Introduction to Flask Templates.

we have created two html files in that article, but the problem is this that we are duplicating

our code in the html files, for example in both html files we have head, body and html tags,

so we need to remove this duplication for 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.

 

 

 

If you are interested in Web Development with Django Framework, than you can read the complete articles in this link,  Django Web Development Tutorials.

 

 

 

OK, we are not going to bring changes in our app.py file, and this is the app.py file.

 

The function render_template provided by Flask integrates the Jinja2 template engine with the application.
This function takes the filename of the template as its first argument.
Any additional arguments are key/value pairs that represent actual values for variables referenced in the template.

 

 

 

So now we need to create our html files,  i assume that you have already created the templates folder, create three html files in the folder, index.html, contact.html and base.html, these are the codes.

 

 

This is 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.

 

 

 

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.

 

 

 

Also this is our contact.html , and we are going to perform the same process as we have done for our index.html.

 

 

 

 

So if you run the code, you will see the same result, but now we have avoided the code duplication in our html files, you can create as much blocks as you want. in this article we have just created two blocks but you can create more blocks according to your requirements.

 

 

 

http://localhost:5000/

Flask Tutorial - Template Inheritance in Flask
Flask Tutorial – Template Inheritance in Flask

 

 

 

 

http://localhost:5000/contact

Flask Template Inheritance
Flask Template Inheritance

 

 

 

 

 

 

Also you can watch my complete 4 hours training on Flask Web Development

 

Subscribe and Get Free Video Courses & Articles in your Email

 

Share via
Copy link
Powered by Social Snap
×