22 lines
621 B
Python
22 lines
621 B
Python
"""模板渲染:从 templates/ 目录加载 .txt 模板并用 str.format 填充。
|
|
|
|
查找顺序:本模块所在目录、当前工作目录。
|
|
"""
|
|
from pathlib import Path
|
|
|
|
_CANDIDATE_DIRS = [Path(__file__).parent / "templates", Path("templates")]
|
|
_cache: dict[str, str] = {}
|
|
|
|
|
|
def _dir() -> Path:
|
|
for d in _CANDIDATE_DIRS:
|
|
if d.is_dir():
|
|
return d
|
|
raise FileNotFoundError("未找到 templates/ 目录")
|
|
|
|
|
|
def render(name: str, **kwargs) -> str:
|
|
if name not in _cache:
|
|
_cache[name] = (_dir() / f"{name}.txt").read_text(encoding="utf-8")
|
|
return _cache[name].format(**kwargs)
|