-
Notifications
You must be signed in to change notification settings - Fork 0
/
template_filler.py
77 lines (54 loc) · 1.87 KB
/
template_filler.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
73
74
75
76
77
template = '{{customerAge}} {{ customerName}} {{ customerName }} '
context = {
"customerName": 'abq',
"customerAge": '12'
}
#
# render(template, context)
# output should be: 12 abq abq
# cases:
# replace double bracketed keys with use passed vaule
# Could be unbalabnced brackets or single >> are strings and should be passed unchanged
# {customerAge} => {customerAge} or { customerAge => { customerAge
# if key not in context {{name}} => ""
# Steps
# make output var (probably list that will be joined on return)
# iterate over string,
# if two consecutive chars are {{ : place on Stack
# continue to push onto the stack untill you find }}
# once closing bracket found, clean string and check if it's in the context
# and replace (or find end of string )
# for all other characters iterate until I find {{
# append slice to output
def replace_keys(temp, context):
"""Return string with {{key}} from temp replaced with context keys value"""
output = []
stack = []
temp_size = len(temp)
idx = 0
while idx <= (temp_size - 1):
char = temp[idx]
if idx + 1 > (temp_size - 1):
next_char = None
else:
next_char = temp[idx+1]
if char == '{' and next_char == '{':
stack.append('{{')
idx += 2
elif char == '}' and next_char == '}':
stack.append('}}')
# check for stack value in our context
temp_key = "".join(stack[1:-1])
temp_key = temp_key.strip()
replace_val = context.get(temp_key, '')
output.append(replace_val)
idx += 2
stack = []
elif len(stack) == 0:
output.append(char)
idx += 1
else:
stack.append(char)
idx += 1
return "".join(output)
print(replace_keys(template, context))