Reputation: 6248
I want to easily reference same-directory templates from arbitrary locations in a flask app, for example:
.
├── app.py
├── src
│ └── thing
│ ├── __init__.py
│ ├── component.html
│ └── component.py
└── templates
Normally, I would have to render_template
referencing the templates
directory and go from there, but this is a pain. How can call the same-directory template consistently with a filepath from something like component.py
, i.e. something like
in component.py
return render_template(self.this_files_directory + "/component.html", data=data)
How can I do this?
Upvotes: 3
Views: 5095
Reputation: 5362
You can reconfigure the default template directory when you instantiate your application object:
from flask import Flask
app = Flask(__name__, template_folder='path/to/templates')
The "Flasky" way to do this, though, would be to use Blueprints to match your directory structure, so within src/thing/__init__.py
:
from flask import Blueprint
bp = Blueprint('thing', __name__, template_folder='src/thing')
from . import component # e.g. your views for the blueprint
Then, within your app.py
you import and register each blueprint:
from flask import Flask
app = Flask(__name__)
from src import thing
app.register_blueprint(thing.bp, url_prefix="/thing")
Also, probably very worthwhile to read through this:
http://flask.pocoo.org/docs/0.12/blueprints/#blueprints
Upvotes: 4