-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.py
67 lines (55 loc) · 1.91 KB
/
template.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
import os
import sys
class redirect:
content = ""
def write(self, str):
self.content += str
def flush(self):
self.content = ""
def parse_template(file_name, context=None):
# Read template content
root_path = os.path.abspath(os.path.dirname(__file__))
path = os.path.join(root_path, "templates", file_name)
with open(path, "r") as f:
html_content = f.read()
# Catch the print content
__console__ = sys.stdout
r = redirect()
sys.stdout = r
# Process template
lines = html_content.split("\n")
processed_lines = []
code_block = ""
in_code_block = False
for i, line in enumerate(lines):
if not in_code_block:
if "{{{" and "}}}" in line:
code_block = line[line.index("{{{") + 3:line.index("}}}")]
if "=" in line:
exec(code_block.strip(), context)
processed_lines.append(lines[i].replace(
"{{{" + code_block + "}}}", str(r.content)))
else:
result = eval(code_block.strip(), context)
processed_lines.append(lines[i].replace(
"{{{" + code_block + "}}}", str(result)))
code_block = ""
r.flush()
elif "{{{" in line:
strip_index = line.index("{{{") + 4
in_code_block = True
else:
processed_lines.append(lines[i])
else:
if "}}}" in line:
exec(code_block, context)
processed_lines.append(str(r.content))
strip_index = 0
code_block = ""
in_code_block = False
r.flush()
else:
code_block += line[strip_index:].rstrip()
code_block += "\n"
sys.stdout = __console__
return "\n".join(processed_lines)