l10n: add sections
This commit is contained in:
@@ -6,19 +6,22 @@ from flask import (
|
||||
request,
|
||||
render_template,
|
||||
)
|
||||
# from flask_babel import Babel, _
|
||||
|
||||
|
||||
translations_cache = {}
|
||||
|
||||
def load_translations(lang):
|
||||
if lang not in translations_cache:
|
||||
translations_cache[lang] = {}
|
||||
|
||||
try:
|
||||
config = ConfigParser()
|
||||
config.read(f'translations/{lang}.ini')
|
||||
translations_cache[lang] = dict(config['messages'])
|
||||
for section in config.sections():
|
||||
translations_cache[lang][section] = dict(config.items(section))
|
||||
except:
|
||||
translations_cache[lang] = {}
|
||||
pass
|
||||
|
||||
return translations_cache[lang]
|
||||
|
||||
|
||||
@@ -26,12 +29,6 @@ def get_locale():
|
||||
return request.accept_languages.best_match(('en', 'ru'), 'en')
|
||||
|
||||
app = Flask(__name__)
|
||||
# app.config['BABEL_DEFAULT_LOCALE'] = 'en'
|
||||
# app.config['BABEL_SUPPORTED_LOCALES'] = ['en', 'ru']
|
||||
# app.jinja_env.add_extension("jinja2.ext.i18n")
|
||||
# app.jinja_env.globals.update(_=lambda x: load_translations("ru")[x])
|
||||
|
||||
# babel = Babel(app, locale_selector=get_locale)
|
||||
|
||||
|
||||
@app.before_request
|
||||
@@ -43,11 +40,20 @@ def before_request():
|
||||
@app.context_processor
|
||||
def inject_translations():
|
||||
def translate(text, **kwargs):
|
||||
template = g.translations.get(text, f"${text}$")
|
||||
if ":" in text:
|
||||
section, key = text.split(":", 1)
|
||||
else:
|
||||
section, key = "messages", text
|
||||
|
||||
template = g.translations \
|
||||
.get(section, {}) \
|
||||
.get(key, f"${section}: {key}$")
|
||||
|
||||
try:
|
||||
return template.format(**kwargs)
|
||||
except:
|
||||
return template
|
||||
|
||||
return {'_': translate}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user