feat: add output filter to copy files to output directory

This commit is contained in:
Corentin 2024-05-20 19:58:48 +02:00
parent a23da83687
commit 562ecf366c
4 changed files with 31 additions and 0 deletions

View File

@ -1,4 +1,5 @@
from pathlib import Path from pathlib import Path
from shutil import copy
from typing import Any from typing import Any
from jinja2.environment import Environment from jinja2.environment import Environment
@ -12,6 +13,7 @@ class Site:
self.__root_directory = root_directory self.__root_directory = root_directory
self.__output_directory = root_directory / "build" self.__output_directory = root_directory / "build"
self.__environment = Environment(loader=FileSystemLoader(searchpath=root_directory / "src")) self.__environment = Environment(loader=FileSystemLoader(searchpath=root_directory / "src"))
self.__environment.filters.update({"output": self.__output})
self.__content = ContentDirectory(root_directory / "content") self.__content = ContentDirectory(root_directory / "content")
@property @property
@ -26,3 +28,16 @@ class Site:
with open(output_path, "w") as output_file: with open(output_path, "w") as output_file:
output_file.write(content) 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}"

View File

@ -17,3 +17,16 @@ def test_render_page(datadir: Path, site_dir: FakeFilesystem):
site.render("index.j2", "index.html") site.render("index.j2", "index.html")
with open(datadir / "build" / "index.html", encoding="utf-8") as ouput_file: with open(datadir / "build" / "index.html", encoding="utf-8") as ouput_file:
assert ouput_file.read() == "<p>Peter</p><p>Steven</p>" assert ouput_file.read() == "<p>Peter</p><p>Steven</p>"
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"

View File

@ -0,0 +1 @@
Yipee

View File

@ -0,0 +1,2 @@
{{ "assets/steven-avatar" | output }}