Created
June 2, 2024 21:38
-
-
Save grahamannett/7ed3a61628da9f8cdec230ca4aa99af7 to your computer and use it in GitHub Desktop.
reflex-component-example.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Component: | |
def __init__(self, *children, **attributes): | |
self.children = children | |
self.attributes = attributes | |
def compile(self, depth=0): | |
tag_name = self.__class__.__name__.lower() | |
attr_str = " ".join( | |
f'{key}="{value}"' for key, value in self.attributes.items() | |
) | |
children_html = "\n".join( | |
child.compile(depth=depth + 1) | |
if isinstance(child, Component) | |
else str(child) | |
for child in self.children | |
) | |
if attr_str: | |
open_tag = f"<{tag_name} {attr_str}>" | |
else: | |
open_tag = f"<{tag_name}>" | |
open_tag = f"{' ' * depth}{open_tag}" | |
close_tag = f"{' ' * depth}</{tag_name}>" | |
children_html = f"{' ' * depth}{children_html}" | |
return f"{open_tag}\n{children_html}\n{close_tag}" | |
class Div(Component): | |
pass | |
class P(Component): | |
pass | |
class Button(Component): | |
pass | |
# Example usage | |
component = Div( | |
P("Text line 1"), | |
Button("Click Me", color="green", font_size="4"), | |
Div(P("Text Line 2", padding="5px", color="blue"), Div(Div("hello"), P("hi"))), | |
) | |
print(component.compile()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment