Coverage for kwai/core/template/jinja2_engine.py: 87%

15 statements  

« prev     ^ index     » next       coverage.py v7.3.0, created at 2023-09-05 17:55 +0000

1"""Modules that implements the template engine interface for jinja2.""" 

2from jinja2 import Environment, FileSystemLoader, TemplatesNotFound, select_autoescape 

3 

4from .jinja2_template import Jinja2Template 

5from .template import Template 

6from .template_engine import TemplateEngine, TemplateNotFoundException 

7 

8JINJA2_FILE_EXTENSION = ".jinja2" 

9 

10 

11class Jinja2Engine(TemplateEngine): 

12 """Implements the TemplateEngine interface for Jinja2.""" 

13 

14 def __init__(self, template_path: str, **kwargs): 

15 """Construct a Jinja2Engine. 

16 

17 kwargs will be merged to the variables that are used to render a template. 

18 Use it for variables that are used in all templates. 

19 """ 

20 self._env = Environment( 

21 loader=FileSystemLoader(template_path), 

22 autoescape=select_autoescape( 

23 disabled_extensions=("txt",), 

24 default_for_string=True, 

25 default=True, 

26 ), 

27 ) 

28 self._variables = kwargs 

29 

30 def create(self, template_file_path: str, lang: str = "nl") -> Template: 

31 """Create a jinja2 template.""" 

32 try: 

33 template = self._env.select_template( 

34 [ 

35 template_file_path + "_" + lang + JINJA2_FILE_EXTENSION, 

36 template_file_path + JINJA2_FILE_EXTENSION, 

37 ] 

38 ) 

39 except TemplatesNotFound as exc: 

40 raise TemplateNotFoundException( 

41 f"Could not find a template with name '{template_file_path}'" 

42 ) from exc 

43 

44 return Jinja2Template(template, **self._variables)