Include another Template in this Template in Python Flask

Flask – Include another template in a template

In a flask application, we can have multiple templates. And sometimes we may need to include one template in another template, like including header and footer templates in another templates.

include keyboard is used to include a template in another template in Flask, as shown in the following expression.

{% include "another-template.html" %}

In this tutorial, we will learn how to include one template in another template with an example flask application.

Example

In this example, we will build a flask application where we have following four templates.

  • header.html
  • footer.html
  • page-1.html
  • page-2.html

Using include keyword, we include header and footer templates in page-1 and page-2 templates.

Project Structure

The following is the structure of our flask application.

Include another Template in this Template in Python Flask

main.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/page-1")
def page_1():
    return render_template("page-1.html")

@app.route("/page-2")
def page_2():
    return render_template("page-2.html")

if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

header.html

<!DOCTYPE html>
<html>
  <style>
    header h1 {
      color: darkgrey;
    }
    h1 {
      color: red;
    }
    h2 {
      color: orange;
    }
    p {
      color:darkgray;
    }
  </style>
  <body>
    <header>
      <h1>Flask Application</h1>
      <hr>
    </header>

footer.html

</body>
</html>

page-1.html

{% include "header.html" %}

<h1>Page 1</h1>
<h2>About</h2>
<p>Welcome to sample flask application.</p>

{% include "footer.html" %}

page-2.html

{% include "header.html" %}

<h1>Page 2</h1>
<h2>Another Page</h2>
<p>This is another page in this flask application.</p>

{% include "footer.html" %}

Terminal

Open terminal at the root of the application, and run the Python file main.py.

Include another Template in this Template in Python Flask

Now, open a browser of your choice and hit the URL http://127.0.0.1:8080/page-1.

Include another Template in this Template in Python Flask

Now, you may hit the URL http://127.0.0.1:8080/page-2 in a browser.

Include another Template in this Template in Python Flask

We have used header.html and footer.html templates in page-1.html and page-2.html templates.

Summary

In this Python Flask Tutorial, we learned how to include another template in a template, with the help of an example flask application.

Related Tutorials

Code copied to clipboard successfully 👍