init: Initial commit
This commit is contained in:
29
modules/template.py
Normal file
29
modules/template.py
Normal file
@@ -0,0 +1,29 @@
|
||||
import os
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
class TemplateEngine:
|
||||
def __init__(self, template_name: str, template_path: str = "templates/") -> None:
|
||||
self.__name = template_name
|
||||
self.__path = template_path
|
||||
self.__template_path = f"{self.__path}{self.__name}.json"
|
||||
self.__template = self.__load_template()
|
||||
|
||||
def __load_template(self) -> dict[str, Any]:
|
||||
with open(self.__template_path, "r", encoding="utf-8") as f:
|
||||
return json.loads(f.read())
|
||||
|
||||
def __replace_placeholders(self, obj: Any, data: dict) -> Any:
|
||||
"""Recursively replace placeholders in dict/list/string values."""
|
||||
if isinstance(obj, dict):
|
||||
return {k: self.__replace_placeholders(v, data) for k, v in obj.items()}
|
||||
elif isinstance(obj, list):
|
||||
return [self.__replace_placeholders(item, data) for item in obj]
|
||||
elif isinstance(obj, str):
|
||||
return obj.format(**data)
|
||||
else:
|
||||
return obj
|
||||
|
||||
def generate(self, data: dict) -> dict[str, Any]:
|
||||
template = self.__load_template()
|
||||
return self.__replace_placeholders(template, data)
|
||||
Reference in New Issue
Block a user