APIarium / app /templates.py
rnilkyway's picture
refactor: extract HTML templates to separate files
c8c52c2
Raw
History Blame Contribute Delete
1.13 kB
import os
from pathlib import Path
from functools import lru_cache
class TemplateLoader:
"""HTML template loader with caching."""
def __init__(self, template_dir: str = "templates"):
self.template_dir = Path(__file__).parent / template_dir
if not self.template_dir.exists():
raise ValueError(f"Template directory not found: {self.template_dir}")
@lru_cache(maxsize=32)
def load(self, name: str) -> str:
"""Load and cache HTML template."""
template_path = self.template_dir / name
if not template_path.exists():
raise FileNotFoundError(f"Template not found: {template_path}")
with open(template_path, 'r', encoding='utf-8') as f:
return f.read()
def render(self, name: str, **kwargs) -> str:
"""Load template and replace placeholders with values."""
html = self.load(name)
for key, value in kwargs.items():
placeholder = f"{{{{{key}}}}}"
html = html.replace(placeholder, str(value))
return html
# Global instance
templates = TemplateLoader()