python-babel / flask-babel

i18n and l10n support for Flask based on Babel and pytz
https://python-babel.github.io/flask-babel/
Other
432 stars 159 forks source link

How to access the language code in a Jinja template? #171

Closed jugmac00 closed 3 years ago

jugmac00 commented 3 years ago

I want to set the language code for e.g. <html lang="xx"> according to the current language.

My current way is to translate the language code

<html lang="{{ _('en') }}">

This feels a bit odd. Shouldn't Flask-Babel offer some variable to access the language code?

alnikolaj commented 3 years ago

I store the current language in a session and pass it to Jinja through a context_processor, see:

@app.context_processor
def inject_language_options():
    return dict(
        current_language = session.get('language',request.accept_languages.best_match(app.config['LANGUAGES'].keys()))
        )

see this Question: https://stackoverflow.com/questions/42393831/how-can-i-choose-the-language-using-flask-babel

jugmac00 commented 3 years ago

Thank you!

So, it seems there are several ways.

Miguel Grinberg uses this one

@app.before_request
def before_request():
    # ...
    g.locale = str(get_locale())

see https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xiii-i18n-and-l10n