zgui

Control flow

Conditionals and keyed lists inside a view — if and for, keys, what is kept and rebuilt, Dynamic, and Portal.

A view is built once, so an ordinary Rust if or for would also run only once. The view grammar has its own if and for, which update what they show when the signals they read change.

Show content conditionally

view! {
    column {
        if move || open.get() {
            box(class = "panel") {"Contents"}
        } else {
            label(class = "hint") {"Nothing selected"}
        }
    }
}

The condition must be a closure. A plain expression is a compile error:

if open.get() { … }         // error: `if` takes a closure
if move || open.get() { … } // correct

This rule prevents a common reactive bug: a condition read once would never change again.

else is optional. Without it, nothing renders while the condition is false. else { } means the same thing.

if move || saving.get() {
    label {"Saving…"}
}

When a branch is rebuilt

The condition runs inside one effect, and zgui compares its result, not the signals it read:

if move || items.get().is_empty() { … } else { … }

Adding a row to a list that already has rows runs the condition again. It returns false again, so nothing changes. The branch is swapped only when the result flips.

  • A hidden branch does not exist. It holds no nodes, signals or timers; it is not hidden with CSS. A branch is built fresh each time it is shown.
  • A shown branch keeps its state while it stays shown. Signals, stored values and defaults created by its components survive any number of condition re-runs that return the same result.
  • If the component containing the if runs again (for example, because it sits in a reactive hole that re-ran), the shown branch is rebuilt in place without swapping nodes. The state it creates is created again along with the component.

Render a list

view! {
    column(class = "list") {
        for item in move || items.get(), key = |item: &Todo| item.id {
            row(class = "todo") {
                text {{item.label.clone()}}
            }
        }
    }
}

A for has three parts:

  1. The row name (item), bound inside the block. It must be a single name, not a pattern; destructure inside the body if you need to.
  2. The collection, after in, written as a closure. It is the list's only reactive dependency.
  3. The key, after a comma, written as key = <closure>. It is required.

Keys

When the collection changes, the list compares the new keys with the old ones to find which rows are new, which are gone, and which moved. Rows are matched by key, not by position:

  • A new key builds a new row.
  • A removed key removes its row and disposes of everything the row created.
  • A key that is still present keeps its row, even if it moved. The row is moved, not rebuilt, so its nodes, scroll position and signals stay with it.

Because a kept row is not rebuilt, plain data captured from the item is not updated when the collection is rewritten with the same key. In the example above, item.label keeps its first value. Put anything that can change in a signal on the item, as shown in the next section. Every row is rebuilt only when the for itself is rebuilt, for example because its component ran again.

The key type must implement Eq + Hash + Clone. Use whatever identifies a row for as long as it exists:

key = |item: &Todo| item.id            // a stable id
key = |name: &String| name.clone()     // the value itself, when it is the identity

Do not key by index: an index is a position, not an identity. Keys must also be unique within one collection; two rows with the same key cause a panic.

Update a single row

Each row has its own scope, which is disposed of when the row is removed. The usual pattern is a collection of items where each item holds signals for the parts that change:

#[derive(Clone, Debug)]
struct Todo {
    id: u64,
    label: String,
    done: RwSignal<bool>,
}

view! {
    for item in move || items.get(), key = |item: &Todo| item.id {
        row(
            class = "todo",
            class:done = move || item.done.get(),
            on:click = move |_| item.done.update(|done| *done = !*done)
        ) {
            text {{item.label.clone()}}
        }
    }
}

Ticking an item writes only that item's done signal. Only that row's class binding reads it, so only that row changes, and the list does not compare keys at all.

Show a placeholder for an empty list

for has no else. To show something when the list is empty, wrap the for in an if:

if move || items.get().is_empty() {
    label(class = "empty") {"Nothing to do yet."}
} else {
    for item in move || items.get(), key = |item: &Todo| item.id {
        row { text {{item.label.clone()}} }
    }
}

Nest control flow

if and for are nodes, so they nest anywhere a node can: inside elements, components, and other control flow.

view! {
    column {
        for row in move || rows.get(), key = |r: &Row| r.id {
            if move || row.visible.get() {
                text {{row.label.clone()}}
            }
        }
    }
}

Switch between several views

Dynamic holds a closure that returns a whole view. It replaces the subtree when the closure's dependencies change:

use zgui::view::{AnyView, Dynamic};

view! {
    box {
        {Dynamic::new(move || match tab.get() {
            Tab::Files => AnyView::new(view! { FileList() }),
            Tab::Search => AnyView::new(view! { SearchPanel() }),
        })}
    }
}

Dynamic::new takes an FnMut() -> AnyView. If the closure returns the same view type as last time, the subtree is updated in place; a different type replaces it.

Use Dynamic for more than two branches of different types. For two branches, prefer if: it compares one boolean, while Dynamic re-runs whenever anything its closure read changes.

Render on an overlay layer

Portal renders its children on an overlay layer instead of where it is written. Dialogs, menus, tooltips and toasts use it so that ancestors cannot clip, transform or stack them.

use zgui::view::{OverlayLayer, Portal};

view! {
    box(class = "row") {
        control(on:click = move |_| open.set(true)) {"Open"}
        if move || open.get() {
            Portal(layer = OverlayLayer::Modal) {
                box(class = "dialog") {"Really delete?"}
            }
        }
    }
}

There are four layers, painted in this order:

LayerFor
OverlayLayer::Contentportalled content that belongs with the page
OverlayLayer::Popoverpopovers, menus, tooltips, dropdowns (the default)
OverlayLayer::Modaldialogs, sheets and drawers
OverlayLayer::Toasttoasts and notices, above everything including dialogs

Because each layer has a fixed order, a toast shown before a dialog still paints above it. The portal leaves a marker where it was written, so its siblings keep their order.

Overlays and portals covers positioning, dismissal and focus.

Show and For

if and for are shorthand for the Show and For components. Both spellings produce the same code:

KeywordComponent
for item in each, key = k { … }For(each = each, key = k, let:item) { … }
if when { … }Show(when = when) { … }
if when { … } else { … }Show(when = when, fallback = move || view! { … }) { … }

Use the component form when the condition is already stored in a variable, because the keyword form needs a closure written in place:

let chosen = move || selection.get().is_some();

view! {
    Show(when = chosen) {
        label {"picked"}
    }
}

when takes impl Fn() -> bool, so the variable must hold a closure. For a Signal<bool>, write move || flag.get().

The keywords expand to For and Show, so those names must be in scope. use zgui::prelude::*; includes both.

For props:

Prop

Type

Show props:

Prop

Type

Unsupported syntax

You writeWrite instead
if open.get() { … }a closure: if move || open.get()
if let Some(x) = y { … }compute the value outside the view, or use a braced child with a match
if a { … } else if b { … }a nested if: else { if move || b { … } else { … } }
if move || a { }an if with a body
if move || a (class = "x") { … }attributes on an element inside the body

else if is not supported because each arm is its own conditional: when the outer result changes, the inner conditional is rebuilt, and nesting makes that visible.

while, loop and match are reserved in views and produce an error that points to for and if.

Next

On this page