close

How to reference a html template from a different directory in python flask

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to reference a html template from a different directory in python flask in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to reference a html template from a different directory in python flask?

  1. How to reference a html template from a different directory in python flask?

    Flask is looking in templates/frontend/src/view_notifications.html for your template file. You either need to move your templates file to that location or change the default template folder.

  2. reference a html template from a different directory in python flask

    Flask is looking in templates/frontend/src/view_notifications.html for your template file. You either need to move your templates file to that location or change the default template folder.

Method 1

Flask is looking in templates/frontend/src/view_notifications.html for your template file. You either need to move your templates file to that location or change the default template folder.

According to the Flask docs you can specify a different folder for your templates. It defaults to templates/ in the root of your app:

import os
from flask import Flask

template_dir = os.path.abspath('../../frontend/src')
app = Flask(__name__, template_folder=template_dir)

UPDATE:

After testing it myself on a Windows machine the templates folder does need to be named templates. This is the code I used:

import os
from flask import Flask, render_template

template_dir = os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
template_dir = os.path.join(template_dir, 'frontend')
template_dir = os.path.join(template_dir, 'templates')
# hard coded absolute path for testing purposes
working = 'C:\Python34\pro\\frontend\\templates'
print(working == template_dir)
app = Flask(__name__, template_folder=template_dir)


@app.route("/")
def hello():
    return render_template('index.html')

if __name__ == "__main__":
    app.run(debug=True)

With this structure:

|-pro
  |- backend
    |- app.py
  |- frontend
    |- templates
      |- index.html

Changing any instance of 'templates' to 'src' and renaming the templates folder to 'src' resulted in the same error OP received.

Method 2

a batter solution is to just go directly without os.path.abspath like this:

from flask import Flask

app = Flask(__name__, template_folder='../../frontend/src')

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read