0

If I now search for 'localhost:5000/?lang=en' or 'localhost:5000/?lang=sv' I can switch between two languages. I use babel for the translation. Now I have written the app like this:

LANGUAGES = ['en', 'sv']

app = Flask(__name__)
app.config["BABEL_DEFAULT_LOCALE"] = LANGUAGES[0]
babel = Babel(app)

@babel.localeselector
def get_locale():
    if request.args.get("lang"):
        session["lang"] = request.args.get("lang")
    return session.get("lang", LANGUAGES[0])

@app.route("/", methods=['GET'])
def index():
    return render_template("index.html", me=me)

and in html file

<form method="GET">
  <input type="submit" name="lang" value="sv">
  <input type="submit" name="lang" value="en">
</form>

I know this is not a good way to do it, but honestly, I do not know how to do it otherwise. Here I have found an example of how I Should be able to solve it, but I have done it so different and after many many hours I have given up trying to do it that way.

What would satisfy me is just

A button that add the text '/?lang=sv' when I press it if it now is 'en' and reverse if current lang is 'sv'

This is acheved now (except that I have 2 buttons instead of one), but if I enter something like 'localhost:5000/?lang=sdfsdf' I get error code 500, witch I do not believe is particularly good to allow, I do not really know where I should add the logic to prevent it, also I know in my heart this is Not the right way of doing it! But it is the best I could come up with.

Salviati
  • 758
  • 2
  • 9
  • 28

1 Answers1

1

You could have radio buttons to select a language of interest rather than having a submit button. The error code 500 isn't a bad thing in this case. You're not able to handle the input and error code 500 means that the server can't process the request. You can either add a custom page for 500 errors, or check in your server side code. Your index function can add the check for query parameters, and handle appropriately rather than just returning the rendered template.

if(LANGUAGES.index(request.args.get("lang")) != -1):
   # do something like set the session['lang'] = 'en'
Eric Yang
  • 2,678
  • 1
  • 12
  • 18
  • Think I have figured it out now. The problem now instead is that when I do {% if LANGUAGES[CURR_LANG]|string() == 'en' %} /*code*/ {% endif %} it throw 'UndefinedError: 'LANGUAGES' is undefined' at me. I am going insane. Edit: CURR_LANG is an int global variable to keep track of witch language I am at – Salviati Jul 25 '18 at 16:23
  • 1
    That code is within your template? If so, you'll need to pass that value into the render_template function render_template('index.html', me=me, LANGUAGES=LANGUAGES'). The template cannot see the variables in the python space unless you manually pass them in. – Eric Yang Jul 25 '18 at 16:53
  • You are a freaking angel. How can I have forgotten that. Would have given you a big sloppy kiss if you were next to me! – Salviati Jul 25 '18 at 16:58