File size: 1,129 Bytes
c8c52c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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()