physical-turing-sim/lib/html_builder.py

68 lines
2.2 KiB
Python
Raw Permalink Normal View History

2024-01-30 20:04:56 +01:00
class HTMLBuilder():
"""
Assembles HTML response through substitution according to the passed dictionary.
The keys need to be in curly braces inside one of the passed files.
The list of files gets glued together in the order they are in, so a head.html
would need to be the first element.
Can be used to glue files without substitution by not passing data dictionary.
Example:
sub_dict = {
"page_title": {
"type": "item",
"value": "My Booklist!"
},
"books": {
"type": "list",
"value": ["Book1", "Book2"]
},
"select": {
"type": "radio",
"value": ["Book1", "Book2"]
}
}
response = HTMLBuilder(["html/head.html", "html/home.html"], sub_dict).build()
:param list files: the files that are glued together in order
:param dict data: the dictionary with which placeholders get replaced
"""
def __init__(self, files: list, data=None) -> None:
self.data = data
self.file: str = ""
for file in files:
self.file += open(file, "r").read()
def build(self) -> bytes:
if self.data == None:
return self.__to_binary()
for key, value in self.data.items():
key = '{' + key + '}'
value_type = value["type"]
value_repl = value["value"]
if value_type == "item":
self.file = self.file.replace(key, value_repl)
if value_type == "list":
repl_string = ""
for litem in value_repl:
repl_string += f'<li>{litem}</li>\n'
self.file = self.file.replace(key, repl_string)
if value_type == "radio":
repl_string = ""
for litem in value_repl:
repl_string += f'<input type="radio" id="1" name="{key[1:-1]}" value="{litem}">\n'
repl_string += f'<label for="{litem}">{litem}</label><br>\n'
self.file = self.file.replace(key, repl_string)
return self.__to_binary()
def __to_binary(self) -> bytes:
return self.file.encode()