From 7761a3b7f08ee62ee247a60a26cb696ed6ede956 Mon Sep 17 00:00:00 2001 From: Ruidy Date: Sun, 4 Jun 2023 11:27:06 +0200 Subject: [PATCH] add config for templatesFolder --- README.md | 3 ++- lib/config.py | 1 + lib/engine.py | 16 ++++++++++++++-- lib/main.py | 6 ++++-- 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 15b64c2..73c44c8 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ The entry point is located in the [main file](./lib/main.py). It should not be modified. -The templates files must be located in the [templates](./templates) directory. +By default, the templates files are located in the [templates](./templates) directory. You can use template inheritance but not yet data injection. ### Configuration @@ -15,6 +15,7 @@ The configuration file ([config.json](./config.json)) is mandatory and should re ```json { "name": "VillaFleurie", + "templatesFolder": "templates", "templates": [ "index.html", "t2-corail.html", diff --git a/lib/config.py b/lib/config.py index 717c650..91bcd17 100644 --- a/lib/config.py +++ b/lib/config.py @@ -4,6 +4,7 @@ from typing import TypedDict class Config(TypedDict): name: str + templatesFolder: str templates: list[str] staticFiles: list[str] outDir: str diff --git a/lib/engine.py b/lib/engine.py index 0b85364..41080cf 100644 --- a/lib/engine.py +++ b/lib/engine.py @@ -1,7 +1,19 @@ +from dataclasses import dataclass +from typing import Protocol + from jinja2 import Environment, FileSystemLoader, select_autoescape engine = Environment(loader=FileSystemLoader("templates"), autoescape=select_autoescape()) -def render(template: str, context: dict | None = None) -> str: - return engine.get_template(template).render(context or {}) +class Renderer(Protocol): + def render(self, template: str, context: dict | None = None) -> str: + ... + + +@dataclass +class FileSystemRenderer(Renderer): + path: str = "templates" + + def render(self, template: str, context: dict | None = None) -> str: + return engine.get_template(template).render(context or {}) diff --git a/lib/main.py b/lib/main.py index f5842c7..29ec149 100644 --- a/lib/main.py +++ b/lib/main.py @@ -6,7 +6,7 @@ from os import path from loguru import logger from lib.config import load -from lib.engine import render +from lib.engine import FileSystemRenderer def main(): @@ -18,6 +18,7 @@ def main(): data = {} destination_path = config["outDir"] + fs = FileSystemRenderer(config.get("templatesFolder")) logger.info(f"🏁 Start building {config['name']}") @@ -28,11 +29,12 @@ def main(): for template in config["templates"]: logger.info(f"📃Render '{template}'") with open(path.join(destination_path, template), "w") as f: - f.write(render(template, data.get(template))) + f.write(fs.render(template, data.get(template))) logger.info("⏩ Start copying staticfiles to build") for folder in config["staticFiles"]: shutil.copytree(folder, f"{config['outDir']}/{folder}") + logger.info("🎉 Done…")