This repository has been archived by the owner on Jan 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 10
/
templating.py
68 lines (61 loc) · 2.28 KB
/
templating.py
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
65
66
67
68
"""
@file
@brief Templating functions
"""
from pprint import pformat
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
if 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\n{}\n"
"---- from text ---\n{}"
"".format(pformat(context), text)) from ee
return res
raise ValueError( # pragma: no cover
f"Engine should be 'mako' or 'jinja2', not '{engine}'.")