Files
LinuxAwesomeBot/templates.py
T

26 lines
834 B
Python

"""模板渲染:从 templates/ 目录加载 .txt 模板并用 str.format 填充。
查找顺序:本模块所在目录、当前工作目录。
文件按修改时间自动热重载,改动后无需重启。
"""
from pathlib import Path
_CANDIDATE_DIRS = [Path(__file__).parent / "templates", Path("templates")]
_cache: dict[str, tuple[float, str]] = {} # name -> (mtime, content)
def _dir() -> Path:
for d in _CANDIDATE_DIRS:
if d.is_dir():
return d
raise FileNotFoundError("未找到 templates/ 目录")
def render(name: str, **kwargs) -> str:
path = _dir() / f"{name}.txt"
mtime = path.stat().st_mtime
cached = _cache.get(name)
if cached is None or cached[0] != mtime:
_cache[name] = (mtime, path.read_text(encoding="utf-8"))
return _cache[name][1].format(**kwargs)