-
Notifications
You must be signed in to change notification settings - Fork 7
/
jinja_manager.py
68 lines (52 loc) · 1.67 KB
/
jinja_manager.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
"""
Jinja2 `Environment` manager.
"""
from pathlib import Path
from typing import Any
import jinja2
from handsdown.exceptions import LoaderError
from handsdown.utils.blackify import blackify
class JinjaManager:
"""
Jinja2 `Environment` manager.
"""
TEMPLATES_PATH = Path(__file__).parent / "templates"
_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(TEMPLATES_PATH.as_posix()),
undefined=jinja2.StrictUndefined,
)
def __init__(self) -> None:
self._env.filters.update({"escape_md": self.escape_md, "blackify": blackify})
@classmethod
def update_globals(cls, **kwargs: object) -> None:
"""
Update global variables in `jinja2.Environment`.
Arguments:
kwargs -- Globals to set.
"""
cls._env.globals.update(kwargs)
@staticmethod
def escape_md(value: str) -> str:
"""
Escape underscore characters.
"""
return value.replace("_", r"\_")
@property
def env(self) -> jinja2.Environment:
"""
Get `jinja2.Environment`.
"""
return self._env
@staticmethod
def trim_eof(value: str) -> str:
"""
Trim EOF newlines and add one newline.
"""
return value.rstrip("\n") + "\n"
def render(self, template_path: Path, **kwargs: Any) -> str:
template_full_path = self.TEMPLATES_PATH / template_path
if not template_full_path.exists():
raise LoaderError(f"Template {template_full_path} not found")
template = self.env.get_template(template_path.as_posix())
result = template.render(**kwargs)
return self.trim_eof(result)