38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
import json
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
|
|
from flask import current_app, session
|
|
from flask_login import current_user
|
|
|
|
|
|
@lru_cache(maxsize=8)
|
|
def load_language(language: str) -> dict:
|
|
base = Path(__file__).resolve().parent.parent / 'static' / 'i18n'
|
|
file_path = base / f'{language}.json'
|
|
if not file_path.exists():
|
|
file_path = base / 'pl.json'
|
|
return json.loads(file_path.read_text(encoding='utf-8'))
|
|
|
|
|
|
def get_locale() -> str:
|
|
if getattr(current_user, 'is_authenticated', False):
|
|
return current_user.language or current_app.config['DEFAULT_LANGUAGE']
|
|
return session.get('language', current_app.config['DEFAULT_LANGUAGE'])
|
|
|
|
|
|
def translate(key: str, default: str | None = None) -> str:
|
|
language = get_locale()
|
|
data = load_language(language)
|
|
if key in data:
|
|
return data[key]
|
|
fallback = load_language(current_app.config.get('DEFAULT_LANGUAGE', 'pl'))
|
|
if key in fallback:
|
|
return fallback[key]
|
|
en = load_language('en')
|
|
return en.get(key, default or key)
|
|
|
|
|
|
def inject_i18n():
|
|
return {'t': translate, 'current_language': get_locale()}
|