Flow control
wybthon.flow¶
flow
¶
Control flow: Show, For, Repeat, Switch/Match, dynamic, and client_only.
Show, For, Repeat, and Switch mount as native regions: one
reactive computation that selects what to render, and an owned scope per
branch or row. There's no wrapper component. A condition or source is
an accessor (or a plain value); children and fallback are nodes or
callables evaluated inside the region's own scope.
When a reactive hole re-renders and returns the same kind of region at the same place, the new condition or source is pushed into the mounted region; branches and rows that are still selected survive.
Callback shapes follow SolidJS 2.0:
Show(when, children): a callablechildrenreceives anAccessorfor the truthy value (or the value itself withkeyed=True).For(each, children, keyed=True):children(item, index)where the shapes depend onkeyed(seeFor).Repeat(count, children):children(index: int).Switch(Match(when, children), ..., fallback=...).dynamic(source): a component whose implementation is chosen reactively.client_only(children, fallback=...): content that only renders in the browser, after hydration.
Example
Classes:
| Name | Description |
|---|---|
Match |
A branch of a |
Functions:
| Name | Description |
|---|---|
Show |
Render |
For |
Render a list with a stable subtree per row. |
Repeat |
Render |
Switch |
Render the first |
dynamic |
Turn an accessor for a component (or tag) into a component you can call. |
client_only |
Render |
is_hydrating |
Whether the browser is adopting server-rendered DOM right now. |
on_hydration_end |
Run |
NoHydration |
Render |
Hydration |
Mark a subtree for hydration; a passthrough in Wybthon. |
Match
¶
Show
¶
Show(when: Callable[[], T | None], children: Callable[[Accessor[T]], object], fallback: Any = None, *, keyed: Literal[False] = False) -> VNode
Show(when: Callable[[], T | None], children: Callable[[T], object], fallback: Any = None, *, keyed: Literal[True]) -> VNode
Show(when: T | None, children: Callable[[Accessor[T]], object], fallback: Any = None, *, keyed: Literal[False] = False) -> VNode
Render children while when is truthy, else fallback.
Only the truthiness of when decides the branch: the branch
re-renders when the condition flips, not on every value change. A
callable children may accept one argument, an
Accessor for the (truthy) value, so inner
holes can read it reactively.
With keyed=True, children re-renders whenever the value itself
changes and receives the raw value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
when
|
Any
|
Condition accessor or plain value. |
required |
children
|
Any
|
A node, a zero-arg callable, or |
None
|
fallback
|
Any
|
Rendered when |
None
|
keyed
|
bool
|
Re-create the branch on every value change. |
False
|
For
¶
For(each: _Each[T], children: Callable[[T, Accessor[int]], object], fallback: Any = None, *, keyed: Literal[True] = True) -> VNode
For(each: _Each[T], children: Callable[[T], object], fallback: Any = None, *, keyed: Literal[True] = True) -> VNode
For(each: _Each[T], children: Callable[[Accessor[T], int], object], fallback: Any = None, *, keyed: Literal[False]) -> VNode
For(each: _Each[T], children: Callable[[Accessor[T]], object], fallback: Any = None, *, keyed: Literal[False]) -> VNode
Render a list with a stable subtree per row.
The mapping callback runs once per row; when the list changes, existing rows keep their DOM and are only moved, never re-diffed. A row's reactive scope is disposed when it leaves the list.
keyed selects how rows are matched, and with it the callback
shape:
True(default): match by identity (scalars by value).children(item, index)receives the raw item and anAccessor[int]index; a callback that takes one parameter gets the item alone.False: match by position.children(item, index)receives anAccessorfor the item at that position and anintindex.- a callable
key(item): match by key, updating the row in place when a new object has the same key.children(item, index)receives accessors for both.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
each
|
Any
|
List accessor (or a plain list, which renders once). |
required |
children
|
Any
|
The row callback. |
required |
fallback
|
Any
|
Rendered when the list is empty. |
None
|
keyed
|
Any
|
Matching strategy. |
True
|
Repeat
¶
Repeat(count: int | Callable[[], int], children: Callable[[int], object], fallback: Any = None, *, start: int | Callable[[], int] = 0) -> VNode
Render children(i) for i in range(start, start + count) with no diffing.
Rendering is driven purely by the count: growing mounts new tail slots, shrinking disposes them, and nothing else is touched. Use it for pagination dots, ratings, skeletons, and other count-driven UI.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
count
|
int | Callable[[], int]
|
Count accessor or plain integer. |
required |
children
|
Callable[[int], object]
|
|
required |
fallback
|
Any
|
Rendered when the count is zero. |
None
|
start
|
int | Callable[[], int]
|
First index (accessor or int). |
0
|
Switch
¶
Render the first Match whose condition is truthy.
Conditions are evaluated in order; only a change in which branch
matches re-renders, so unrelated value changes are ignored (unless a
branch is keyed).
dynamic
¶
Turn an accessor for a component (or tag) into a component you can call.
The returned callable behaves like any component: call it with
children and props to get a VNode. Each instance re-mounts when
source resolves to a different component; while source is an
async computation with no value yet, the instance keeps its current
content and the nearest Loading shows its
fallback. Passing None renders nothing.
This is the counterpart of SolidJS 2.0's dynamic(). For a one-off
use, call the result inline: dynamic(lambda: views[kind()])(title="Hi").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
Any
|
An accessor returning a component, a tag name, or
|
required |
client_only
¶
Render children only in the browser, after hydration.
During a server render, and while the browser hydrates that render,
fallback shows instead; the children replace it as soon as
hydration has committed. In a page that wasn't server-rendered,
the children render immediately. Use it for widgets that need
browser APIs or whose output depends on the browser (a map, a chart
measured from the viewport, the user's local time).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
children
|
Any
|
A node or a zero-arg callable returning the content. |
required |
fallback
|
Any
|
What the server renders, and what shows until hydration finishes. |
None
|
is_hydrating
¶
is_hydrating() -> bool
Whether the browser is adopting server-rendered DOM right now.
True only during the synchronous mount of hydrate:
render what the server rendered, then switch to client-only values
from on_settled. Always false on the server and in pages that
weren't server-rendered.
on_hydration_end
¶
Run callback once the browser has finished hydrating the page.
Registered while hydrate mounts, it runs after
the hydrated page has committed. Registered anywhere else (a page
that wasn't server-rendered, or after hydration), it runs on the
next tick. It doesn't say hydration succeeded, only that it's over.
During a server render it does nothing. Matches Solid 2.0's
onHydrationEnd.
NoHydration
¶
Render children on the server as static HTML the browser won't hydrate.
While the browser hydrates, the region's server-rendered DOM is kept as is and nothing inside it is mounted, so it costs no Python work and never updates. In a page that wasn't server-rendered, the children render normally. Use it for content that never changes after the first paint: article bodies, footers, legal text.
Matches Solid 2.0's <NoHydration>.
Hydration
¶
Mark a subtree for hydration; a passthrough in Wybthon.
Solid 2.0 uses <Hydration> to re-enable hydration for an island
inside <NoHydration>. Wybthon keeps a NoHydration region static
as a whole while hydrating, so this renders its children unchanged.
It's provided so code shared with Solid's model reads the same.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*children
|
Any
|
The content. |
()
|
id
|
str | None
|
Accepted for parity; unused. |
None
|
What's in this module¶
Control-flow primitives that create isolated reactive scopes, so only
the relevant subtree updates when a condition or list changes.
Conditions and sources are accessors, getters, or plain values, and
children and fallback slots are nodes or callables evaluated inside
the primitive's own scope. All arguments are positional except the
keyword-only options noted below. In a compiled template, a call such as
{Show(count() > 5, ...)} or {For(todos(), row)} receives each
dynamic argument as a getter, exactly as a component does, so the
condition or source stays reactive without a lambda. Content written as
markup or a component call is made lazy, so a hidden branch is never
built.
Show, For, Repeat, and Switch mount as native regions, not
wrapper components: each is one computation that selects what to
render, plus an owned scope per branch or row. There's no component
context or props object. When a reactive hole re-renders and returns
the same kind of region in the same place, the new condition or source
is pushed into the mounted region, so branches and rows that are still
selected survive.
| Name | Description |
|---|---|
Show |
Show(when, children, fallback=None, *, keyed=False): render one branch by truthiness. |
For |
For(each, children, fallback=None, *, keyed=True): one cached row per item; rows move, never re-diff. |
Repeat |
Repeat(count, children, fallback=None, *, start=0): children(i) for i in range(start, start + count). |
Switch / Match |
Switch(Match(when, children, keyed=False), ..., fallback=None): first truthy branch wins. |
dynamic |
dynamic(source): a component whose implementation (a component or tag) is chosen by a reactive source. Call the result with children and props. |
client_only |
client_only(children, *, fallback=None): render children only in the browser, after hydration; fallback renders on the server. |
NoHydration |
NoHydration(*children): server-rendered HTML the browser keeps as static DOM instead of hydrating. |
Hydration |
Hydration(*children, id=None): a passthrough kept for parity with Solid 2.0. |
is_hydrating |
True only during the synchronous mount of hydrate. |
on_hydration_end |
on_hydration_end(callback): run callback once the page has finished hydrating (on the next tick when nothing is hydrating; never during a server render). |
For keying shapes¶
keyed selects how rows are matched between updates, and with it the
callback shape:
keyed |
Rows match by | children(item, index) receives |
|---|---|---|
True (default) |
Identity (scalars by value) | the raw item, Accessor[int] |
False |
Position | Accessor[T], int |
key(item) callable |
The key; a new object with the same key updates the row in place | Accessor[T], Accessor[int] |
The row callback runs once per row inside the row's owner scope and
untracked; anything reactive inside a row belongs in a template
expression, memo, or effect. With the default keying, the index
accessor is the row itself, and the signal behind it is only created
when something reads i() in a tracking scope. Passing a plain list for
each (a name bound to a list, not an accessor or a compiled
expression) renders once and warns in dev mode. A store
list can be passed as is.
Typed callbacks¶
For and Show have generic overloads, so type checkers infer the
callback's parameters from the source (Repeat's callback is typed as
taking an int):
| Call | Inferred parameters |
|---|---|
For(todos(), lambda todo, i: ...) |
todo: Todo, i: Accessor[int] |
For(todos(), lambda todo, i: ..., keyed=False) |
todo: Accessor[Todo], i: int |
For(todos(), lambda todo, i: ..., keyed=lambda t: t.id) |
todo: Accessor[Todo], i: Accessor[int] |
Show(user, lambda u: ...) |
u: Accessor[User] |
Show(user, lambda u: ..., keyed=True) |
u: User |
For accepts the list or an accessor for it, and both infer the same
row type. A callback inside a call ({For(todos(), lambda todo, i: ...)})
may be a bare lambda; only a lambda that is the whole interpolation
needs parentheses. Pass the accessor to Show (Show(user, ...)) when
its callback takes the value.
from wybthon import For, Match, Repeat, Show, Switch, create_signal, html
todos, set_todos = create_signal([{"id": 1, "title": "Ship", "done": False}])
status, set_status = create_signal("ready")
rating, set_rating = create_signal(3)
user, set_user = create_signal(None)
def greeting(u):
return html(t"<li>Hello, {u()['name']}</li>")
def numbered(todo, i):
return html(t"<li>{i() + 1}. {todo['title']}</li>")
def live_title(todo, i):
return html(t"<li>{todo()['title']}</li>")
loading = html(t"<li>Loading...</li>")
ready = html(t"<li>Ready</li>")
unknown = html(t"<li>Unknown</li>")
view = html(t"""
<ul>
{Show(user, greeting, fallback=html(t"<li>Sign in</li>"))}
{For(todos(), numbered)}
{For(todos(), live_title, keyed=lambda t: t["id"])}
<li>{Repeat(rating(), lambda i: html(t"<span>*</span>"), start=1)}</li>
{Switch(Match(status() == "loading", loading), Match(status() == "ready", ready), fallback=unknown)}
</ul>
""")
Showtracks only the truthiness ofwhen; a callablechildrenmay take the value accessor (or the raw value withkeyed=True, which re-creates the branch on every change).ShowandSwitchare one branch computation that re-mounts only when the selected branch changes.childrenandfallbackmay be nodes, such as templates, or callables. A node branch is mounted afresh each time it's selected. The compiler makes the content and fallback ofShow,Match,Switch(its fallback), andclient_onlylazy when they're written as markup (html(t"...")) or a component call (a capitalized callee): each becomes a zero-argument function, so a branch is built only when it shows. Names, lambdas, and lowercase calls, likegreetingandloadingabove, are passed as written. See Lazy branches.Repeatis driven purely by the count: growing mounts tail slots, shrinking disposes them, and nothing else is touched.countandstartmay be accessors or ints.dynamicaccepts a tag name, a component,None, or an accessor returning one of those; each instance remounts when the resolved component changes.client_onlyrenders its fallback during a server render and while hydrating, then its children; see Server rendering. For one-off work after hydration (starting a widget that measures the DOM, say), register it withon_hydration_end.NoHydrationcosts no Python work while hydrating: the kernel keeps the region's server DOM as is (CLAIM_STATIC) and nothing inside it mounts or updates. In a page that wasn't server-rendered, its children render normally.
See also¶
map_arrayandrepeat: the reactive mapping behindForandRepeatcreate_projection: per-row selection that notifies only the changed rows- Concepts: Components
- Guides: Authoring patterns
- Guides: Performance