A template loader that loads from a single root directory.
| 451 | |
| 452 | |
| 453 | class Loader(BaseLoader): |
| 454 | """A template loader that loads from a single root directory.""" |
| 455 | |
| 456 | def __init__(self, root_directory: str, **kwargs: Any) -> None: |
| 457 | super().__init__(**kwargs) |
| 458 | self.root = os.path.abspath(root_directory) |
| 459 | |
| 460 | def resolve_path(self, name: str, parent_path: Optional[str] = None) -> str: |
| 461 | if ( |
| 462 | parent_path |
| 463 | and not parent_path.startswith("<") |
| 464 | and not parent_path.startswith("/") |
| 465 | and not name.startswith("/") |
| 466 | ): |
| 467 | current_path = os.path.join(self.root, parent_path) |
| 468 | file_dir = os.path.dirname(os.path.abspath(current_path)) |
| 469 | relative_path = os.path.abspath(os.path.join(file_dir, name)) |
| 470 | if relative_path.startswith(self.root): |
| 471 | name = relative_path[len(self.root) + 1 :] |
| 472 | return name |
| 473 | |
| 474 | def _create_template(self, name: str) -> Template: |
| 475 | path = os.path.join(self.root, name) |
| 476 | with open(path, "rb") as f: |
| 477 | template = Template(f.read(), name=name, loader=self) |
| 478 | return template |
| 479 | |
| 480 | |
| 481 | class DictLoader(BaseLoader): |