Skip to content

Declarative HTML Elements

Alberto Ruiz edited this page Nov 12, 2025 · 1 revision

TeaLeaf provides a declarative Python API for building HTML pages — no templates, no strings. Each HTML tag is represented by a Python function, and attributes, styles, or child elements are defined using a clean, chainable syntax.

Basic example

from TeaLeaf.Html.Elements import html, head, body, h1, div, button

page = html(
    head(),
    body(
        h1("Welcome to TeaLeaf!"),
        div("This content is rendered from Python."),
        button("Click me!")
    )
)

Each HTML tag in TeaLeaf is represented by a Python function They all share the same pattern:

div(children...)         # create a <div>
div().attr(name=value)   # add an attribute
div().classes("a", "b")  # add CSS classes
div().style(color="red") # inline style

Attirbutes

Attributes are added using .attr() it accepts any standard HTML attribute or event handler:

button("Save").attr(id="saveBtn", onclick="alert('Saved!')")
form().attr(action="/submit", method="POST")
input().attr(name="email", placeholder="Enter your email")

Classes and style

TeaLeaf makes it easy to assign classes or inline styles:

div("Hello").classes("card", "highlight")
h1("Title").style(color="green", text_align="center")

Event handling

Since TeaLeaf integrates with its reactivity layer, event attributes like onclick can be tied to Store actions or custom JavaScript code.

from TeaLeaf.Magic.MagicComponent import rButton
from TeaLeaf.Magic.Store import Store

store = Store({"counter": 0})

div(
    rButton("-").attr(onclick=store.do.update("counter", -1)),
    h1(store.react("counter")),
    rButton("+").attr(onclick=store.do.update("counter", 1)),
)

Here, the buttons directly update a reactive Store, and the counter re-renders automatically in the browser. No manual JS required.

Dynamic content

You can insert any Python value or expression as a child:

user = "Alb"
div(f"Hello {user}!")  # produces <div>Hello Alb!</div>

Lists of elements are supported:

div(
    [h2(f"Item {i}") for i in range(5)]
)

Common helpers

TeaLeaf includes a few specialized helpers that map to common patterns:

Function Description
textInput() creates an <input type="text">
submit(label) <input type="submit" value="label">
checkbox(checked=False) <input type="checkbox">
link() <link> tag for stylesheets
script(code) <script> tag
header() , footer() semantic layout tags

Composition and reuse

You can define reusable components as simple Python functions:

def Card(title, content):
    return div(
        h2(title),
        div(content)
    ).classes("card").style(padding="10px")

@app.route("/")
def home():
    return html(
        body(
            Card("Welcome", "This is a TeaLeaf component."),
            Card("Info", "Reusable and declarative!")
        )
    )

Clone this wiki locally