Replace templates templates templates on the fly in flask

I would like to replace the templates folder associated with my Blueprint and originally registered with this Blueprint into my Flask app. I've tried the following:

from flask import current_app as app

bp = Blueprint('myblueprint', __name__, template_folder='templates/en', url_prefix='/<lang_code>')

@bp.before_request
def verify_language():
    # check if there are any parameters in the url and get lang_code
    url_params = request.view_args
    lang = (url_params and url_params.pop('lang_code', None)) or None
    # if lang_code is given, make sure it is valid
    if lang in ['en', 'fi']:
        if lang == 'fi':
            app.blueprints["myblueprint"].template_folder = 'templates/fi'
        else:
            app.blueprints["myblueprint"].template_folder = 'templates/en'
        g.lang_code = lang
    else:
        return jsonify({"error": "Invalid Parameters (lang_code)"})

@bp.url_defaults
def add_language_code(endpoint, values):
    values.setdefault('lang_code', g.lang_code)

      

I have similar .html files with the same names in the "templates / en" and "templates / fi" folders, with the obvious exception that the site text has been translated into two different languages.

This works once when I login to my site, but then it stops working. So, as soon as I enter my site and change the url prefix lang_code to "fi", I can see my Finnish site, but replacing "en" in the url no longer shows me the English site.

I think it has something to do with Flask adding the Blueprint templates folders to the app's search path and then finding the first match for "X.html" I have in my

return render_template('X.html')

      

Is there a way to actually replace the Blueprint template folder registered with the app, i.e. delete the first one by adding the other?

+3


source to share





All Articles