Include in a Flask template

If you have gotten involved in making templates in Flask it is easy for you to want to reuse code and need to put an include in a template Flask. In this example we are going to explain how this task can be carried out.

The first thing is to create the code to reuse. The code is still a piece HTML, in this case we are going to create a footer.html

<footer>
    <hr/>
    Page created by <a href="https://lineadecodigo.com">Línea de Code</a>. © 2016
</footer>

We are going to put the footer.html file inside the templates directory. As an organization we have created an inc subdirectory to save it.

/templates/inc/footer.html

Now we go to our template in Flask and what we have to use is a structure:

{% include '/path/file_to_inluir.html' %}

It is important that the path and the file to include is from the base of the directory. In the case that we are coding, the following would have to be added:

{% include '/inc/footer.html' %}

In this way, our application that creates an include in a template Flask would have three parts:

Program: hello.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def greeting():
    name = 'Victor'
    return render_template('hello_footer.html',name=name)

if __name__ == '__main__':
    app.run()

Template: /templates/hello_footer.html

<!DOCTYPE html>
<html lang="es">
<head>
<title>Hello World</title>
</head>
<body>

Hello {{ name }}

{% include '/inc/footer.html' %}

</body>
</html>

Code to Reuse: /templates/inc/footer.html

<footer>
    <hr/>
    Page created by <a href="https://lineadecodigo.com">Línea de Code</a>. © 2016
</footer>

Leave a Comment