-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevaluate.py
72 lines (55 loc) · 1.95 KB
/
evaluate.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
69
70
71
72
# This file provides nodes for the parser to use.
import html
class TemplateError(Exception):
pass
class Node:
pass
class GroupNode(Node):
def __init__(self, children):
self.children = children
def returnText(self, context):
try:
avar = []
strr = ""
for node in self.children:
avar.append(node.returnText(context))
return strr.join(avar)
except NameError as e:
raise TemplateError("The template attmepted to render an undefined variable: {}".format(e.args), " the available variables were: {}".format(context))
class TextNode(Node):
def __init__(self, text):
self.text = text
def returnText(self, context):
return self.text
class PyNode(Node):
def __init__(self, text):
self.text = text
def returnText(self, context):
return html.escape(str(eval(self.text, {}, context)))
class IfNode(Node):
def __init__(self, predicate, group):
self.predicate = predicate
self.group = group
def returnText(self, context):
if eval(self.predicate, {}, context) == True:
return self.group.returnText(context)
else:
return ""
class ForNode(Node):
def __init__(self, variable, iterable, groupnode):
self.iterable = iterable
self.variable = variable
self.groupnode = groupnode
def returnText(self, context):
result = ""
for i in eval(self.iterable, {}, context):
context["__itervar"] = i
exec(self.variable + " = __itervar", {}, context)
result += self.groupnode.returnText(context)
return result
if __name__ == '__main__':
x = PyNode(" name ")
print(x.returnText({'title': 'Foobar'}))
# {% for x in blah %}{{ x*x }}{% end for %}
g = IfNode()
print(g.returnText({'blah': [1, 2, 5]}))