Coverage for src/content_generator/template_engine.py: 79%

1"""模板引擎."""

2

3 from __future__ import annotations

4

5 from typing import Any

6

7 from jinja2 import BaseLoader, Environment, FileSystemLoader

8

9

10 class TemplateEngine:

11 def __init__(self, template_dir: str | None = None) -> None:

12 if template_dir:

13 self.env = Environment(loader=FileSystemLoader(template_dir))

14 else:

15 self.env = Environment(loader=BaseLoader())

16

17 def render(self, template_str: str, context: dict[str, Any]) -> str:

18 template = self.env.from_string(template_str)

19 return template.render(**context) # type: ignore[no-any-return]

20

21 def render_file(self, template_file: str, context: dict[str, Any]) -> str:

22 template = self.env.get_template(template_file)

23 return template.render(**context) # type: ignore[no-any-return]