Nested Components

Compose components by nesting them inside each other. Every nested component is a fully independent instance with its own state, so a tree can go as deep as you like without anything leaking across levels.

Nesting to any depth

A component can even render itself. This NestedBox drops in a child of the same type on every click, so you can build an arbitrarily deep tree at runtime. Name a box, add a nested one, and keep going: each level holds its own live input, proving every instance is isolated.

PREVIEW
Level 1
class NestedBox(Component):
    children: list = []
    level: int = 0
    label: str = ""

    def mount(self):
        self.level += 1  # deepen one level per nesting

    def add_box(self):
        self.children.append(len(self.children) + 1)

    def inline_template(self):
        return """
        <div class="...">
            <span>Level {{ level }}</span>
            <input lace:model.live="label" placeholder="name this box">
            <button lace:click="add_box">+ Nest</button>

            {% for key in children %}
                {% interlace "NestedBox" key=key level=level %}
            {% endfor %}
        </div>
        """

Child-to-parent events

Nesting is not just layout, children can talk back. A child calls emit_to, addressing its parent by name, and the parent handles it. Here each row emits to the list to remove itself.

PREVIEW
Write the docs
Ship it
class NestList(Component):
    items: list = ["Write the docs", "Ship it"]
    draft: str = ""

    def add(self):
        if self.draft.strip():
            self.items.append(self.draft.strip())
            self.draft = ""

    def remove_item(self, payload):
        # Called when a child emits "remove_item"
        self.items.pop(payload["index"])

    def inline_template(self):
        return """
        <div class="...">
            <input lace:model="draft">
            <button lace:click="add">Add</button>
            {% for item in items %}
                {% interlace "NestRow" key=forloop.counter0 label=item index=forloop.counter0 %}
            {% endfor %}
        </div>
        """
class NestRow(Component):
    label: str = ""
    index: int = 0

    def remove(self):
        # Emit to the parent, addressed by component name
        self.emit_to("NestList", "remove_item", {"index": self.index})

    def inline_template(self):
        return """
        <div class="...">
            <span>{{ label }}</span>
            <button lace:click="remove">✕</button>
        </div>
        """

To broadcast to every listening component instead of one named parent, use emit. See Events for the full event API.

View this page as markdown - handy as context for your AI tools. Full index at /llms.txt.

Theme
Accent
Ink