Skip to content

Commit

Permalink
added Jinja2Core
Browse files Browse the repository at this point in the history
  • Loading branch information
RootShinobi committed Jun 29, 2024
1 parent f2ded0b commit cd35798
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 0 deletions.
3 changes: 3 additions & 0 deletions aiogram_i18n/cores/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,21 @@
from .fluent_compile_core import FluentCompileCore
from .fluent_runtime_core import FluentRuntimeCore
from .gnu_text_core import GNUTextCore
from .jinja2_core import Jinja2Core


__cores__ = {
"GNUTextCore": ".gnu_text_core",
"FluentRuntimeCore": ".fluent_runtime_core",
"FluentCompileCore": ".fluent_compile_core",
"Jinja2Core": ".jinja2_core",
}

__all__ = (
"GNUTextCore",
"FluentRuntimeCore",
"FluentCompileCore",
"Jinja2Core",
"BaseCore",
)

Expand Down
55 changes: 55 additions & 0 deletions aiogram_i18n/cores/jinja2_core.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from pathlib import Path
from typing import Any, Dict, Optional, Union

from aiogram_i18n.cores.base import BaseCore
from aiogram_i18n.exceptions import KeyNotFoundError, NoModuleError
from aiogram_i18n.utils.text_decorator import td

try:
from jinja2 import Environment, Template
except ImportError as e:
raise NoModuleError(name="Jinja2Core", module_name="jinja2") from e


class Jinja2Core(BaseCore[Dict]):
environment: Environment

def __init__(
self,
path: Union[str, Path],
default_locale: Optional[str] = None,
environment: Optional[Environment] = None,
raise_key_error: bool = True,
use_td: bool = True,
locales_map: Optional[Dict[str, str]] = None,
) -> None:
super().__init__(path=path, default_locale=default_locale, locales_map=locales_map)
self.environment = environment or Environment(autoescape=True)
if use_td:
for name, func in td.functions.items():
self.environment.filters[name.lower()] = func
self.raise_key_error = raise_key_error

def get(self, message_id: str, locale: Optional[str] = None, /, **kwargs: Any) -> str:
locale = self.get_locale(locale=locale)
translator: Dict[str, Template] = self.get_translator(locale=locale)
try:
message = translator[message_id]
except KeyError:
if locale := self.locales_map.get(locale):
return self.get(message_id, locale, **kwargs)
if self.raise_key_error:
raise KeyNotFoundError(message_id) from None
return message_id
return message.render(kwargs)

def find_locales(self) -> Dict[str, Dict]:
translations: Dict[str, Dict[str, Template]] = {}
locales = self._extract_locales(self.path)
for locale, paths in self._find_locales(self.path, locales, ".j2").items():
translations[locale] = {}
for file_path in paths:
with file_path.open(encoding="utf-8") as f:
translations[locale][file_path.stem] = self.environment.from_string(f.read())

return translations
4 changes: 4 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ compiler = [
runtime = [
"fluent.runtime~=0.4.0",
]
jinja2 = [
"jinja2~=3.1.4",
]
test = [
"pytest~=7.4.0",
"pytest-cov~=4.0.0",
Expand Down Expand Up @@ -85,6 +88,7 @@ post-install = [
features = [
"compiler",
"runtime",
"jinja2",
"dev",
"test",
"docs",
Expand Down

0 comments on commit cd35798

Please sign in to comment.