I made it with another language site using flask-babel, so I documented how to make it
I referred to this site, but some of them were written about 5 years ago and do not match the current situation. So I modified it a little.
The sample code is posted on github here. https://github.com/shibacow/flask_babel_sample (Actually, this alone may have achieved the intent of this blog). I think it works if I clone the above repository and put Flask and Flask-Babel in it.
flask-babel is a library for realizing i18n with flask. The site of flask-babel is here
Install using pip as follows
pip install Flask-Babel
You can go with the original site.
https://github.com/shibacow/flask_babel_sample/blob/master/srv.py
of
@babel.localeselector
def get_locale():
return request.accept_languages.best_match(['ko','zh','ja', 'ja_JP', 'en'])
Can be automatically determined with.
https://github.com/shibacow/flask_babel_sample/blob/master/templates/hello.html
Like,
<p>
message: {{ gettext('Hello world!') }}
</p>
Prepare a sentence enclosed in gettext like. You may use `_ ()`
like message: {{_ ('Hello world!')}}` `. This
'Hello world!'` `` Is the target of the replacement wording.
After that, prepare babel.cfg as shown in this article,
$ pybabel extract -F babel.cfg -k lazy_gettext -o messages.pot .
$ pybabel init -i messages.pot -d translations -l ja
You can create a ja folder under translations.
With a similar feeling
$ pybabel init -i messages.pot -d translations -l en
$ pybabel init -i messages.pot -d translations -l zh
$ pybabel init -i messages.pot -d translations -l ko
And so on. Language locale names such as ko and zh seem to be determined by the code ISO-639-1 (https://ja.wikipedia.org/wiki/ISO_639-1%E3%82%B3%E3%83% BC% E3% 83% 89% E4% B8% 80% E8% A6% A7)
Then
https://github.com/shibacow/flask_babel_sample/blob/master/translations/ja/LC_MESSAGES/messages.po
Can be done. Open messages.po and put the translated wording in msgid under msgid. msgid is included, but msgid is not included, so fill in the wording you translated yourself.
After translating all the languages
$ pybabel compile -d translations
Compile with. If the word fuzzy is included in /messages.po, it will not be compiled (it is considered to be in the process of translation), so remove the word fuzzy from messages.po.
After compiling, you will have messages.mo.
https://github.com/shibacow/flask_babel_sample/blob/master/translations/ja/LC_MESSAGES/messages.mo
It looks like a binary file.
If you execute python srv.py
in this state, the part that originally contains Hello World will be changed depending on the language selection of the browser.
And
It will be replaced with the translated language.
Recommended Posts