Elements & Events
Alongside HTML templates, WebComPy lets you construct DOM trees directly in Python via webcompy.elements. Python element trees give you full IDE autocomplete, type checking, dynamic composition, and direct control over keyed list updates and conditional branches.
At a glance#
from webcompy import use_computed, use_state
from webcompy.components import ComponentContext, define_component
from webcompy.elements import DOMEvent, html
@define_component()
def StepperControl(context: ComponentContext[None]):
step = use_state(lambda: 1)
def increment(_ev: DOMEvent):
step.value += 1
return html.DIV(
{"class": "stepper"},
html.SPAN({}, use_computed(lambda: f"Step: {step.value}")),
html.BUTTON({"type": "button", "@click": increment}, "+1"),
)
The html namespace and element structure#
Every HTML tag is available as an uppercase factory on html (e.g., html.DIV, html.P, html.BUTTON, html.INPUT, html.UL, html.LI):
- First argument: attributes dictionary (
{"class": "card", "disabled": is_disabled, "@click": on_click}). - Remaining arguments (
*children): strings,Elements,Components,SignalBasevalues, orNone(skipped). - Boolean & reactive attributes: passing
Truesets a valueless boolean attribute (disabled); passingFalseorNoneomits it. Any attribute value can be aSignalorComputedthat stays synced with the DOM.
Text, line breaks, raw HTML, and fragments#
text(val, enable_multiline=True)renders a text node (splitting newlines into<br>whenenable_multiline=True).break_line()creates a<br>node.raw_html(html_str_or_signal, wrapper="span")injects raw HTML inside a wrapper element — only use this with trusted markup.- Returning a
listortupledirectly from a component acts as a fragment with multiple sibling root nodes.
Conditional rendering with switch()#
Render the first matching reactive branch without tearing down surrounding elements:
from webcompy import use_computed, use_state
from webcompy.elements import html, switch
status = use_state(lambda: "loading")
view = switch(
{"case": use_computed(lambda: status.value == "loading"), "generator": lambda: html.P({}, "Loading...")},
{"case": use_computed(lambda: status.value == "ready"), "generator": lambda: html.P({}, "Ready!")},
default=lambda: html.P({}, "Idle"),
)
Each branch takes a {"case": signal, "generator": lambda: ...} mapping and an optional default=lambda: ... fallback. Generators run lazily only when that branch becomes active.
Lists and keyed reconciliation with repeat()#
Render reactive lists (ReactiveList) or reactive dicts (ReactiveDict) using repeat(sequence, template, key=None):
from webcompy import use_reactive_list
from webcompy.elements import html, repeat
todos = use_reactive_list(
lambda: [
{"id": 1, "text": "Write docs"},
{"id": 2, "text": "Run tests"},
]
)
todo_list = html.UL(
{},
repeat(
todos,
lambda item, _key: html.LI({}, item["text"]),
key=lambda item: item["id"],
),
)
- Keyed lists (
key=): pass a function returning a unique stable key (intorstr) from each item. Whenkey=is provided,templatereceives(item, derived_key)and WebComPy reuses existing DOM nodes across insertions, deletions, and reorders instead of rebuilding the whole list. - Plain
ReactiveListwithoutkey=:templatereceives(item,)(or(item, index)). ReactiveDict: keys are already intrinsic, so omitkey=and accept(value, dict_key)or(value,)intemplate.
DOM events and DOMEvent#
Prefix event keys with "@" inside an element's attributes mapping ("@click", "@input", "@submit", "@keydown", or event("click")):
from webcompy.elements import DOMEvent, html
def handle_submit(ev: DOMEvent):
ev.preventDefault()
ev.stopPropagation()
print("Submitted!")
html.FORM({"@submit": handle_submit}, html.BUTTON({"type": "submit"}, "Send"))
Handlers receive a DOMEvent wrapping the browser event (ev.target, ev.preventDefault(), ev.stopPropagation()). Event handlers may also be async def coroutines — WebComPy schedules them automatically and routes uncaught exceptions to any ancestor ErrorBoundary.
Capturing DOM nodes with DomNodeRef#
When you need imperative browser DOM access (focusing an <input>, measuring dimensions, integrating a canvas/chart library), attach a DomNodeRef using noderef (or ":ref"):
from webcompy.components import ComponentContext, define_component, on_mounted
from webcompy.elements import DomNodeRef, html, noderef
@define_component()
def AutoFocusSearch(context: ComponentContext[None]):
input_ref = DomNodeRef()
@on_mounted
def focus_on_mount():
input_ref.focus()
return html.INPUT({noderef: input_ref, "type": "search", "placeholder": "Search..."})
DomNodeRef proxies attribute access and method calls directly to the mounted DOM node (input_ref.focus()), or exposes the underlying DOMNode via input_ref.element (raising WebComPyException if accessed before mount).
Notes & caveats#
- Always call
input_refinside@on_mountedor event handlers, not directly during initial component setup before the DOM element exists. - Prefer keyed
repeat(..., key=...)for lists of interactive rows or inputs so focus and element state stay attached to the right item across reorders.
Next steps#
- See how WebComPy renders Markdown files into element trees in Markdown Documents.
- Compare Python element helpers with HTML Templates.
- Use
:bindand first-party form controls in Forms. - Full API: Elements, Routing & DI API.