feat: add Site class to render pages

This commit is contained in:
Corentin 2024-05-20 12:14:09 +02:00
parent bf443a39e1
commit 1f1037dd01
6 changed files with 57 additions and 3 deletions

View File

@ -16,7 +16,8 @@ class Content:
class ContentDirectory(Content):
def load(self, subpath: Path) -> Content:
def load(self, subpath: str | Path) -> Content:
subpath = Path(subpath)
current: Content = self
for part in subpath.parts:
if not isinstance(current, ContentDirectory):

28
jwebsite/site.py Normal file
View File

@ -0,0 +1,28 @@
from pathlib import Path
from typing import Any
from jinja2.environment import Environment
from jinja2.loaders import FileSystemLoader
from jwebsite.content import ContentDirectory
class Site:
def __init__(self, root_directory: Path) -> None:
self.__root_directory = root_directory
self.__output_directory = root_directory / "build"
self.__environment = Environment(loader=FileSystemLoader(searchpath=root_directory / "src"))
self.__content = ContentDirectory(root_directory / "content")
@property
def content(self) -> ContentDirectory:
return self.__content
def render(self, source: str, output: str | Path, **context: Any) -> None:
self.__output_directory.mkdir(parents=True, exist_ok=True)
template = self.__environment.get_template(source)
content = template.render(site=self, **context)
output_path = self.__output_directory / output
with open(output_path, "w") as output_file:
output_file.write(content)

View File

@ -14,16 +14,18 @@ dependencies = [
"click",
"jinja2",
"markdown",
"pyyaml",
"markdown-full-yaml-metadata",
"marshmallow",
"pyyaml",
]
[project.optional-dependencies]
dev = [
"nox",
"pyfakefs",
"pytest",
"pytest-datadir",
"pytest-coverage",
"pytest-datadir",
]
[project.scripts]

19
tests/test_site.py Normal file
View File

@ -0,0 +1,19 @@
from pathlib import Path
from pyfakefs.fake_filesystem import FakeFilesystem
from pytest import fixture
from jwebsite.site import Site
@fixture
def site_dir(datadir: Path, fs: FakeFilesystem):
fs.add_real_directory(datadir)
yield fs
def test_render_page(datadir: Path, site_dir: FakeFilesystem):
site = Site(datadir)
site.render("index.j2", "index.html")
with open(datadir / "build" / "index.html", encoding="utf-8") as ouput_file:
assert ouput_file.read() == "<p>Peter</p><p>Steven</p>"

View File

@ -0,0 +1 @@
[Peter, Steven]

View File

@ -0,0 +1,3 @@
{%- for otter in site.content.load('otters.yml') -%}
<p>{{ otter }}</p>
{%- endfor %}