I am studying flask.render_template(template_name_or_list, **context) and amazed by its ability to use the keywords from **context to get them evaluated in the template's {{ expression }}. I tried to implement this [concept][1] with RegEx, but only ok with simple variables:
import re
context = {"page_title" : "this is my title", "page_body" : "this is my body"}
Ks = list(context.keys())
newL = []
with open('homePage.html', 'r') as html:
for line in html:
for key in Ks:
y = re.search(f"(.*){{{{[ \t]*{key}[ \t]*}}}}(.*)", line)
if y:
line = y.group(1) + context[key] + y.group(2)
newL.append(line)
with open('homePage3.html', 'w') as html:
html.writelines(newL)
I know flask {{arg}} can work on any type of variables and valid expressions like f.string's {arg} does.
return render_template('form.html', fruit=fruit(apples=23, oranges=32))
<p>I have {{ fruit.apples }} apples and {{ fruit.oranges }} oranges.</p>
<p>There are {{ fruit.apples + fruit.oranges }} fruits.</p>
<p>The vendor for apples is {{ fruit.vendor['apples'].name }}</p>
<p>The vendor for oranges is {{ fruit.vendor['oranges'].name }}</p>
My question is does it come up with "context['fruit'].vendor['oranges'].name" with the key fruit is replaced with its value or it uses some other methods to convert them to f.string or string.format?
[1]: https://stackoverflow.com/questions/46725789/flask-render-template