mockapi/services/template_service.py
2026-03-16 05:47:01 +00:00

41 lines
No EOL
1.3 KiB
Python

import jinja2
from jinja2.sandbox import SandboxedEnvironment
from typing import Any, Dict
class TemplateService:
"""
Service for rendering Jinja2 templates with variable resolution.
Uses a sandboxed environment with StrictUndefined to prevent security issues
and raise errors on undefined variables.
"""
def __init__(self):
self.env = SandboxedEnvironment(
undefined=jinja2.StrictUndefined,
autoescape=False, # We're not rendering HTML
trim_blocks=True,
lstrip_blocks=True,
)
def render(self, template: str, context: Dict[str, Any]) -> str:
"""
Render a Jinja2 template with the provided context.
Args:
template: Jinja2 template string.
context: Dictionary of variables to make available in the template.
Returns:
Rendered string.
Raises:
jinja2.TemplateError: If template syntax is invalid or rendering fails.
"""
try:
jinja_template = self.env.from_string(template)
return jinja_template.render(**context)
except jinja2.TemplateError as e:
# Re-raise with additional context
raise jinja2.TemplateError(f"Failed to render template: {e}") from e