Localized Flask-Babel strings inside js

I am new to both Python and Flask (with Jinja2 as a template engine), and I'm not sure if I am doing this correctly. I am using the Flask-Babel extension to add i18n support to my web application. I want to get localized strings from my js code, for example:

var helloWorld = gettext('Hello, world');
console.log(helloWorld); //should log a localized hello world message

For this, I configured babel (babel.cfg):

[python: **/**.py]
[jinja2: **/**.html]
extensions=jinja2.ext.autoescape,jinja2.ext.with_
[javascript: **/**.js]
encoding = utf-8

And its initialization (import is omitted for simplicity):

#main Flask app
app = Flask(__name__)

#localization
babel = Babel(app)

LANGUAGES = {
    'ca': 'Catalan',
    'en': 'English',
    'de': 'Deutsch',
    'es': 'Español',
    'fi': 'Finnish',
    'it': 'Italian'
}

@babel.localeselector
def get_locale():
    return request.accept_languages.best_match(LANGUAGES.keys())

#some more stuff...

Babel identifies this line when creating the POT / PO language files, but it seems that I cannot access these localized lines from the js code, because the gettext function is not defined. Jinja2 seems to be ignoring this part.

Any clues?

+4
source share
1

- , , . , javascript- html-, Jinja2 Jinja2, . js , .

, gettext :

var helloWorld = {{gettext('Hello, world')}};

, , , js- :

var helloWorld = Hello, world;

. .

hello_world.html:

<script type="text/javascript">
   var x = {{gettext('Hello, world')|generate_string|safe}};
   console.log(x);    //logs the localized hello world message
</script>

app.py:

#Jinja2 filters
from jinja2 import evalcontextfilter, Markup

#Mind the hack! Babel does not work well within js code
@app.template_filter()
@evalcontextfilter
def generate_string(eval_ctx, localized_value):
    if localized_value is None:
        return ""
    else:
        return Markup("\"" + localized_value + "\"").unescape()

, !

+2

Source: https://habr.com/ru/post/1531365/


All Articles