Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

""" 

@file 

@brief Templating functions 

""" 

 

 

class CustomTemplateException(Exception): 

""" 

Raised when a templatre could not compile. 

""" 

pass 

 

 

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

""" 

Extend a string containing templating instructions. 

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

 

@param text text 

@param context local variable to use 

@param engine 'mako' or 'jinja2' 

@return resulting text 

""" 

if engine == "mako": 

from mako.template import Template 

from mako.exceptions import CompileException 

try: 

tmpl = Template(text) 

except CompileException as ee: 

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

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

import mako.exceptions 

exc = mako.exceptions.text_error_template() 

text = exc.render() 

raise CustomTemplateException( 

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

try: 

res = tmpl.render(**context) 

except Exception as ee: 

import mako.exceptions 

exc = mako.exceptions.text_error_template() 

text = exc.render() 

raise CustomTemplateException( 

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

return res 

elif engine == "jinja2": 

from jinja2 import Template 

from jinja2.exceptions import TemplateSyntaxError, UndefinedError 

try: 

template = Template(text) 

except TemplateSyntaxError as eee: 

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

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

raise CustomTemplateException( 

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

try: 

res = template.render(**context) 

except UndefinedError as ee: 

raise CustomTemplateException( 

"Some parameters are missing or mispelled.") from ee 

return res 

else: 

raise ValueError( 

"engine should be 'mako' or 'jinja2', not '{0}'".format(engine))