Skip to content

Instantly share code, notes, and snippets.

@ozcanyarimdunya
Last active May 15, 2022 21:56
Show Gist options
  • Save ozcanyarimdunya/18cb57ed9dc425af742cdc4659068a23 to your computer and use it in GitHub Desktop.
Save ozcanyarimdunya/18cb57ed9dc425af742cdc4659068a23 to your computer and use it in GitHub Desktop.
Build html with python
class Element:
tag = None
def __init__(self, *elements, **attrs):
self.elements = elements
self.attrs = attrs
assert self.tag is not None, "Set tag property!"
def html(self):
attrs = []
for k, v in self.attrs.items():
attrs.append(f'{k}="{v}"')
attrs = " ".join(attrs)
if attrs:
html = f"<{self.tag} {attrs}>"
else:
html = f"<{self.tag}>"
for element in self.elements:
if isinstance(element, Element):
text = element.html()
else:
text = str(element)
html += text
html += f"</{self.tag}>"
return html
def __str__(self):
return self.html()
class Td(Element):
tag = "td"
class Th(Element):
tag = "th"
class Tr(Element):
tag = "tr"
class Table(Element):
tag = "table"
class P(Element):
tag = "p"
class Div(Element):
tag = "div"
elem = Div(
P("Hello, World!"),
Table(
Tr(Th("Text 1", colspan="2")),
Tr(Td("Id"), Td("Name")),
Tr(Td("1"), Td("Item 1")),
Tr(Td("2"), Td("Item 2")),
),
Table(
Tr(Th("Text 2", colspan="2")),
Tr(Td("Id"), Td("Name")),
Tr(Td("1"), Td("Item 1")),
),
Table(
Tr(Th("Text 3", colspan="2")),
Tr(Td("Id"), Td("Name")),
Tr(Td("1"), Td("Item 1")),
Tr(Td("2"), Td("Item 2")),
),
)
print(elem.html())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment