diff --git a/app.py b/app.py index 72e752b..24732cb 100644 --- a/app.py +++ b/app.py @@ -1,7 +1,55 @@ from os import system as console -from flask import Flask, render_template +from configparser import ConfigParser +from flask import ( + Flask, + g, + request, + render_template, +) +# from flask_babel import Babel, _ + + +translations_cache = {} + +def load_translations(lang): + if lang not in translations_cache: + try: + config = ConfigParser() + config.read(f'translations/{lang}.ini') + translations_cache[lang] = dict(config['messages']) + except: + translations_cache[lang] = {} + return translations_cache[lang] + + +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 +def before_request(): + g.locale = get_locale() + g.translations = load_translations(g.locale) + + +@app.context_processor +def inject_translations(): + def translate(text, **kwargs): + template = g.translations.get(text, f"${text}$") + try: + return template.format(**kwargs) + except: + return template + return {'_': translate} + if app.debug: console("sass static/style/main.scss static/style/main.css") diff --git a/requirements.txt b/requirements.txt index 4aac190..239bd48 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ Flask==3.1.1 +Flask-Babel gunicorn diff --git a/templates/footer.tmpl b/templates/footer.tmpl index 72dae32..f44d890 100644 --- a/templates/footer.tmpl +++ b/templates/footer.tmpl @@ -1,5 +1,5 @@ \ No newline at end of file diff --git a/templates/header.tmpl b/templates/header.tmpl index 4aec285..4aa02db 100644 --- a/templates/header.tmpl +++ b/templates/header.tmpl @@ -1,8 +1,8 @@