Coverage for an_website/utils/template_loader.py: 100.000%
18 statements
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-16 19:56 +0000
« prev ^ index » next coverage.py v7.6.4, created at 2024-11-16 19:56 +0000
1# This program is free software: you can redistribute it and/or modify
2# it under the terms of the GNU Affero General Public License as
3# published by the Free Software Foundation, either version 3 of the
4# License, or (at your option) any later version.
5#
6# This program is distributed in the hope that it will be useful,
7# but WITHOUT ANY WARRANTY; without even the implied warranty of
8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
9# GNU Affero General Public License for more details.
10#
11# You should have received a copy of the GNU Affero General Public License
12# along with this program. If not, see <https://www.gnu.org/licenses/>.
14"""A tornado template loader."""
16from __future__ import annotations
18import os.path
19from importlib.resources.abc import Traversable
20from typing import override
22from tornado.template import BaseLoader, Template
25class TemplateLoader(BaseLoader):
26 """A tornado template loader."""
28 root: Traversable
30 def __init__(self, root: Traversable, whitespace: None | str) -> None:
31 """Initialize the template loader."""
32 self.root = root
33 super().__init__(whitespace=whitespace)
35 @override
36 def _create_template(self, name: str) -> Template:
37 """Create a template from the given name."""
38 return Template((self.root / name).read_bytes(), name=name, loader=self)
40 @override
41 def resolve_path(self, name: str, parent_path: str | None = None) -> str:
42 """Resolve the template path.
44 name is interpreted as relative to parent_path if it's not None.
45 """
46 if (
47 # same check as in tornado.template.Loader
48 parent_path
49 and not parent_path.startswith("<")
50 and not parent_path.startswith("/")
51 and not name.startswith("/")
52 ):
53 return os.path.normpath(
54 os.path.join(os.path.dirname(parent_path), name)
55 )
56 return name