Files
lair.moe/modules/locale.py
T
Sweetbread 4d92bc2adb
Docker Build and Push / build-and-push (push) Failing after 36s
Move locale things into module
2026-01-17 21:51:33 +03:00

48 lines
1.1 KiB
Python

from configparser import ConfigParser
from flask import g, request
translations_cache = {}
def load_translations(lang):
if lang not in translations_cache:
translations_cache[lang] = {}
try:
config = ConfigParser()
config.read(f'locale/{lang}.ini')
for section in config.sections():
translations_cache[lang][section] = dict(config.items(section))
except:
pass
return translations_cache[lang]
def get_locale():
return request.accept_languages.best_match(
('en', 'ru', 'de', 'fr', 'ja'),
) or 'en'
def before_request():
g.locale = get_locale()
g.translations = load_translations(g.locale)
def inject_translations():
def translate(text, **kwargs):
if ":" in text:
section, key = text.split(":", 1)
else:
section, key = "common", text
template = g.translations \
.get(section, {}) \
.get(key, f"${section}: {key}$")
try:
return template.format(**kwargs)
except:
return template
return {'_': translate}