I'm testing out Flask with blueprints. My app has two blueprints:
base/__init__.py
base = Blueprint('base', __name__, static_folder='static', template_folder='templates')
#http://server.com/base
opinions/__init__.py
opinions = Blueprint('opinions', __name__, static_folder='static', template_folder='templates')
#http://server.com/opinions
__init__.py
app = Flask(__name__)
from app.base import views
from app.base import base
app.register_blueprint(base, url_prefix='/base')
from app.opinions import views
from app.opinions import opinions
#app.register_blueprint(opinions, url_prefix='/opinions') <-- Uncommenting this line causes issues
If I register only 1 of these blueprints, everything runs fine. However, if I register both blueprints, templates are always loaded from opinions
. For example if I hit http://server.com/base , the index.html gets picked from opinions folder. Flask documentation does not mention anything about 'template_folder' namespace conflicts.
PS - I would like to know alternative ways of handling multiple blueprints. I'm not very comfortable importing views
file from two different blueprints. Whats the better way to do this?
Blueprint template directories are registered globally. They share one namespace so that your app can override the blueprint's template if necessary. This is mentioned briedly in the documentation.
Thus, you should not name your opinions' template index.html
, but rather opinions/index.html
. That makes for awkward paths at first glance (…/opinions/templates/opinions/…
) but adds flexibility for customizing "canned" templates without changing the blueprint's contents.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With