3

I would like to substitute the templates-folder associated with my Blueprint and originally registered with that Blueprint to my Flask app. I have 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 identical names under the "templates/en" and "templates/fi" folder, with the obvious exception that the site text has been translated to two different languages.

This works for one time when I enter my site, but then it stops working. So, once I enter my site and change the url-prefix lang_code to be "fi", I see my finnish site, but substituting "en" in the url does not show me the English site anymore.

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

return render_template('X.html')

Is there a way to really substitute the Blueprint template folder registered to the app i.e. remove the first one while adding the other?

rize
  • 849
  • 6
  • 17
  • 33
  • I was searching much https://stackoverflow.com/questions/49496761/two-language-flask-site-with-or-without-blueprints/49948870#49948870 this is what I did. – Beqa Bukhradze May 01 '18 at 06:55

0 Answers0