Open In App
Related Articles

Template Inheritance in Flask

Improve Article
Save Article
Like Article

Template inheritance is a very good feature of Jinja templating . Jinja is a web template engine for the Python programming language . We have seen that webpages of a website contains same footer , navigation bar etc.  So instead of making same footer and navigation bar in all webpages separately , we make use of template inheritance , which allows us to create the part which is same in all webpages (eg. footer,navigation bar) only once and we also don’t need to write the html , head , title tag again and again . Lets define the common structure of web pages in base.html file. First of all we will render  template using flask from file .

Prerequisite –  Flask – (Creating first simple application)


Step 1 – Create a flask app to render the main template 


from flask import Flask, render_template
# Setting up the application
app = Flask(__name__)
# making route
def home():
    return render_template('home.html')
# running application
if __name__ == '__main__':

Step 2 – Create HTML Files

Now we will set up our base.html file in which we have one heading which will be common in all webpages. 

Syntax : 

{% block content %}
{% endblock %}

The code above and below these lines will be the same for every web pages and the code between them will be for a specific web page . 


<!DOCTYPE html>
<html lang="en">
    <title>Template Inheritance</title>
    <h1> This heading is common in all webpages </h1>
    {% block content %}
    {% endblock %}


Now we will set up our home.html file in which we will inherit template from “base.html” file and will write some code for 

home page also . 

Syntax :

  {% extends "base.html" %}
        {% block content %}
          write code here for home page only 
        {% endblock %}


{%extends "base.html" %}
{%block content%}
<h1>Welcome to Home</h1>
{% endblock %}


Run your file . 

Output – 

Below is the output.


This article is just a simple example. We can also add navigation bar , footer , etc to base.html file and can inherit to home.html file and many others .

Last Updated : 05 Sep, 2020
Like Article
Save Article
Similar Reads
Related Tutorials