(self, template_dirs: str | list[str], app_url: str)
| 13 | |
| 14 | class ViewService: |
| 15 | def __init__(self, template_dirs: str | list[str], app_url: str) -> None: |
| 16 | self.app_url = app_url |
| 17 | if isinstance(template_dirs, str): |
| 18 | template_dirs = [template_dirs] |
| 19 | |
| 20 | existing_dirs = [] |
| 21 | for template_dir in template_dirs: |
| 22 | if not os.path.exists(template_dir): |
| 23 | raise NotFoundException( |
| 24 | error_no=ErrorNo.TEMPLATE_DIR_NOT_FOUND, |
| 25 | message=f"Failed to find template directory: {template_dir}", |
| 26 | ) |
| 27 | |
| 28 | existing_dirs.append(template_dir) |
| 29 | |
| 30 | self.env = Environment( |
| 31 | loader=FileSystemLoader(existing_dirs), |
| 32 | autoescape=select_autoescape(["html", "xml"]), |
| 33 | trim_blocks=True, |
| 34 | lstrip_blocks=True, |
| 35 | enable_async=True, |
| 36 | ) |
| 37 | |
| 38 | self.env.filters.update( |
| 39 | { |
| 40 | "format_date": ViewService._format_date, |
| 41 | "format_currency": ViewService._format_currency, |
| 42 | "truncate_words": ViewService._truncate_words, |
| 43 | "json_dump": json.dumps, |
| 44 | } |
| 45 | ) |
| 46 | |
| 47 | self.env.globals.update( |
| 48 | { |
| 49 | "year": datetime.now().year, |
| 50 | "date": datetime.now().strftime("%d.%m.%Y"), |
| 51 | "app_url": app_url, |
| 52 | "url": partial(ViewService._format_url, base_url=app_url), |
| 53 | } |
| 54 | ) |
| 55 | |
| 56 | self.template_dirs = existing_dirs |
| 57 | self._cache: dict[str, Template] = {} |
| 58 | |
| 59 | async def render_template(self, template_name: str, context: dict[str, Any] | None = None) -> str: |
| 60 | if context is None: |
nothing calls this directly
no test coverage detected