Coverage for pyquickhelper/texthelper/templating.py: 100%

36 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-03 02:21 +0200

1""" 

2@file 

3@brief Templating functions 

4""" 

5from pprint import pformat 

6 

7 

8class CustomTemplateException(Exception): 

9 """ 

10 Raised when a templatre could not compile. 

11 """ 

12 pass 

13 

14 

15def apply_template(text, context, engine="mako"): 

16 """ 

17 Extend a string containing templating instructions. 

18 See :epkg:`mako` or :epkg:`jinja2`. 

19 

20 @param text text 

21 @param context local variable to use 

22 @param engine 'mako' or 'jinja2' 

23 @return resulting text 

24 """ 

25 if engine == "mako": 

26 from mako.template import Template 

27 from mako.exceptions import CompileException 

28 try: 

29 tmpl = Template(text) 

30 except CompileException as ee: 

31 mes = ["%04d %s" % (i + 1, _) 

32 for i, _ in enumerate(text.split("\n"))] 

33 import mako.exceptions 

34 exc = mako.exceptions.text_error_template() 

35 text = exc.render() 

36 raise CustomTemplateException( 

37 "unable to compile with mako\n{0}\nCODE:\n{1}".format(text, "\n".join(mes))) from ee 

38 try: 

39 res = tmpl.render(**context) 

40 except Exception as ee: 

41 import mako.exceptions 

42 exc = mako.exceptions.text_error_template() 

43 text = exc.render() 

44 raise CustomTemplateException( 

45 "Some parameters are missing or mispelled.\n" + text) from ee 

46 return res 

47 

48 if engine == "jinja2": 

49 from jinja2 import Template 

50 from jinja2.exceptions import TemplateSyntaxError, UndefinedError 

51 try: 

52 template = Template(text) 

53 except TemplateSyntaxError as eee: 

54 mes = ["%04d %s" % (i + 1, _) 

55 for i, _ in enumerate(text.split("\n"))] 

56 raise CustomTemplateException( 

57 "unable to compile with jinja2\n" + "\n".join(mes)) from eee 

58 try: 

59 res = template.render(**context) 

60 except UndefinedError as ee: 

61 raise CustomTemplateException( 

62 "Some parameters are missing or mispelled\n{}\n" 

63 "---- from text ---\n{}" 

64 "".format(pformat(context), text)) from ee 

65 return res 

66 

67 raise ValueError( # pragma: no cover 

68 f"Engine should be 'mako' or 'jinja2', not '{engine}'.")