|
| 1 | +from pathlib import Path |
| 2 | +from typing import Any, Dict, Optional, Union |
| 3 | + |
| 4 | +from aiogram_i18n.cores.base import BaseCore |
| 5 | +from aiogram_i18n.exceptions import KeyNotFoundError, NoModuleError |
| 6 | +from aiogram_i18n.utils.text_decorator import td |
| 7 | + |
| 8 | +try: |
| 9 | + from jinja2 import Environment, Template |
| 10 | +except ImportError as e: |
| 11 | + raise NoModuleError(name="Jinja2Core", module_name="jinja2") from e |
| 12 | + |
| 13 | + |
| 14 | +class Jinja2Core(BaseCore[Dict]): |
| 15 | + environment: Environment |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + path: Union[str, Path], |
| 20 | + default_locale: Optional[str] = None, |
| 21 | + environment: Optional[Environment] = None, |
| 22 | + raise_key_error: bool = True, |
| 23 | + use_td: bool = True, |
| 24 | + locales_map: Optional[Dict[str, str]] = None, |
| 25 | + ) -> None: |
| 26 | + super().__init__(path=path, default_locale=default_locale, locales_map=locales_map) |
| 27 | + self.environment = environment or Environment(autoescape=True) |
| 28 | + if use_td: |
| 29 | + for name, func in td.functions.items(): |
| 30 | + self.environment.filters[name.lower()] = func |
| 31 | + self.raise_key_error = raise_key_error |
| 32 | + |
| 33 | + def get(self, message_id: str, locale: Optional[str] = None, /, **kwargs: Any) -> str: |
| 34 | + locale = self.get_locale(locale=locale) |
| 35 | + translator: Dict[str, Template] = self.get_translator(locale=locale) |
| 36 | + try: |
| 37 | + message = translator[message_id] |
| 38 | + except KeyError: |
| 39 | + if locale := self.locales_map.get(locale): |
| 40 | + return self.get(message_id, locale, **kwargs) |
| 41 | + if self.raise_key_error: |
| 42 | + raise KeyNotFoundError(message_id) from None |
| 43 | + return message_id |
| 44 | + return message.render(kwargs) |
| 45 | + |
| 46 | + def find_locales(self) -> Dict[str, Dict]: |
| 47 | + translations: Dict[str, Dict[str, Template]] = {} |
| 48 | + locales = self._extract_locales(self.path) |
| 49 | + for locale, paths in self._find_locales(self.path, locales, ".j2").items(): |
| 50 | + translations[locale] = {} |
| 51 | + for file_path in paths: |
| 52 | + with file_path.open(encoding="utf-8") as f: |
| 53 | + translations[locale][file_path.stem] = self.environment.from_string(f.read()) |
| 54 | + |
| 55 | + return translations |
0 commit comments