Skip to content

Instantly share code, notes, and snippets.

@xcombelle
Last active July 31, 2023 16:25
Show Gist options
  • Save xcombelle/b48b3b4b5150a150309a5bb5565236cf to your computer and use it in GitHub Desktop.
Save xcombelle/b48b3b4b5150a150309a5bb5565236cf to your computer and use it in GitHub Desktop.
une autre manière de faire un template
[<!DOCTYPE html>]
[<html>]
for item in itemlist:
[<li>{item}</li>]
[</html>]
[<!-- tout ce qui se trouve entre crochet est ajouté au template, le reste s'execute come code executabel standard-->]
t'''<!DOCTYPE html>
<html>
<head>
<script>alert('hello world');</script>
'''
for item in itemlist:
t'<li>{item}</li>'
t'</html>'
t'<!-- tout ce qui se trouve entre dans t'....' est ajouté au template, le reste s'execute come code executabel standard-->'
def template(s):
zero_or_more(s,
token)
def zero_or_more(s,value):
while token(s):
if len(s.chars )== s.index:
break
pass
return True
def token(s):
if string(s):
return True
if (c:=s.chars[s.index]) in " \t\r\n":
p(c)
s.index+=1
return True
p(s.chars[s.index])
s.index+=1
return True
def string(s):
do(s,
starts_string,
string_content,
ends_string
)
def starts_string(s):
if s.chars[s.index] == "[":
p('result.append(f"')
s.index+=1
return True
else:
return False
def ends_string(s):
if s.chars[s.index] == "]":
p('")')
s.index+=1
return True
else:
return False
def string_content(s):
while s.chars[s.index] != "]":
if s.chars[s.index] == "{":
p("{escape(")
elif s.chars[s.index] == "}":
p(")}")
else:
p(s.chars[s.index])
s.index+=1;
return True
def do(s,
*args):
for arg in args:
if arg(s):
continue
else:
return False
return True
class S:
pass
code=""
def p(arg):
global code
code+=arg
s=S()
s.chars="""
[<!DOCTYPE html>]
[<html>]
for item in itemlist:
[<li>{item}</li>]
[</html>]
"""
s.index = 0
template(s)
result=[]
def escape(value):
import html
return html.escape(value)
print(code)
exec(code,None,{"result":result,"escape":escape,"itemlist":["A","B","C"]})
print("".join(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment