diff --git a/jwebsite/site.py b/jwebsite/site.py index 61935de..93de39d 100644 --- a/jwebsite/site.py +++ b/jwebsite/site.py @@ -1,4 +1,5 @@ from pathlib import Path +from shutil import copy from typing import Any from jinja2.environment import Environment @@ -12,6 +13,7 @@ class Site: self.__root_directory = root_directory self.__output_directory = root_directory / "build" self.__environment = Environment(loader=FileSystemLoader(searchpath=root_directory / "src")) + self.__environment.filters.update({"output": self.__output}) self.__content = ContentDirectory(root_directory / "content") @property @@ -26,3 +28,16 @@ class Site: with open(output_path, "w") as output_file: output_file.write(content) + + def __output(self, path: str | Path) -> str: + path = Path(path) + if path.is_absolute(): + src_path = path + relative_src_path = src_path.relative_to(self.__content.path) + else: + src_path = self.__content.path / path + relative_src_path = path + dst_path = self.__output_directory / relative_src_path + dst_path.parent.mkdir(parents=True, exist_ok=True) + copy(src_path, dst_path, follow_symlinks=True) + return f"/{relative_src_path}" diff --git a/tests/test_site.py b/tests/test_site.py index 6d00504..3b75eb5 100644 --- a/tests/test_site.py +++ b/tests/test_site.py @@ -17,3 +17,16 @@ def test_render_page(datadir: Path, site_dir: FakeFilesystem): site.render("index.j2", "index.html") with open(datadir / "build" / "index.html", encoding="utf-8") as ouput_file: assert ouput_file.read() == "
Peter
Steven
" + + +def test_output_file(datadir: Path, site_dir: FakeFilesystem): + site = Site(datadir) + build_dir = datadir / "build" + + site.render("output-file.j2", "output-file.html") + + with open(build_dir / "assets/steven-avatar", encoding="utf-8") as ouput_file: + assert ouput_file.read() == "Yipee\n" + + with open(build_dir / "output-file.html", encoding="utf-8") as ouput_file: + assert ouput_file.read() == "/assets/steven-avatar\n" diff --git a/tests/test_site/content/assets/steven-avatar b/tests/test_site/content/assets/steven-avatar new file mode 100644 index 0000000..1c2028f --- /dev/null +++ b/tests/test_site/content/assets/steven-avatar @@ -0,0 +1 @@ +Yipee diff --git a/tests/test_site/src/output-file.j2 b/tests/test_site/src/output-file.j2 new file mode 100644 index 0000000..4117c47 --- /dev/null +++ b/tests/test_site/src/output-file.j2 @@ -0,0 +1,2 @@ +{{ "assets/steven-avatar" | output }} +