zgui

Views

Writing interface with the view! macro — elements, text, expressions, children, attributes, and views as values.

In zgui you describe the interface with the view! macro: a tree of elements, text, and components written as nested calls. The views on this page are fixed. Reactivity in views shows how parts of a view follow state.

view! is optional: it expands to ordinary builder calls. To write views without it, see Without macros.

A first view

use zgui::prelude::*;

view! {
    column(class = "card") {
        label(class = "card__title") {"Storage"}
        row(class = "card__row") {
            text {"Used"}
            spacer()
            text {"41 GB"}
        }
    }
}

Each node is a name followed by an attribute list, a children block, or both.

column(class = "card"){ … }
column
The name of an element or component.
(class = "card")
A comma-separated attribute list in parentheses.
{ … }
The children block in braces.
The parts of a view node

You can leave out either part, but not both:

view! {
    spacer()             // attributes only (here, none)
    label {"Total"}      // children only
    label() {"Total"}    // the same, written out
    label {}             // no attributes, no children
}

A bare name such as spacer is not a node. The compiler error suggests what you probably meant: spacer() for an element, {spacer} for a variable, or "spacer" for text.

cargo fmt does not format the inside of view!, because its contents are not Rust expressions. Indent by hand and keep one node per line.

Text, expressions, and calls

The first token of a node decides what kind of node it is.

You writeIt isExample
a string literaltext"Save"
a braced expressiona value converted into a view{label}
an identifiera call to an element or a componentrow(...)

Text

A string literal is a text child. It needs no element around it.

label {"Save"}

Expressions

A braced child holds one expression, and its value is converted into a view.

let title = String::from("Storage");

view! {
    label {{title}}                        // a String
    text {{format!("{n} left")}}           // any expression
    box {{maybe_footer}}                   // an Option renders nothing when None
}

The double braces are intentional: the outer pair is the children block and the inner pair is the expression. Types you can put in a view lists what a braced child can hold.

An expression without braces is not a child. column { item.label.clone() } fails because item is read as the start of a call. Write column { {item.label.clone()} }. The same applies to macros: write {format!("{n} left")}.

Elements and components

An identifier starts a call. The case of the name decides what is called:

  • A lower-case name is an element, such as row, text or control. zgui has sixteen of them, listed in Elements.
  • An upper camel case name is a component, such as Counter or Card: a Rust function you wrote. See Components.

A name can also be a path, for components in other modules or elements you define yourself:

ui::Button()         // a component from another module
html::div()          // an element from your own set

Hyphens in an element name become underscores (overlay-root() calls overlay_root()), and Rust keywords work as names: box() is the element named box.

Children

Children are written one after another, with no commas and no closing tags. Nesting works the same at every level.

row {
    "a"
    {b}
    column()
}

A { after an attribute list is always that call's children block, even on the next line. The macro cannot see line breaks:

vector(class = "axes")
{"x"}                    // a child of `vector`, not a sibling

Add an empty block to keep them apart:

vector(class = "axes") {}
{"x"}                    // now a sibling

Attributes

Attributes go inside the parentheses as name = value, separated by commas. A trailing comma is allowed.

control(
    class = "button",
    tabindex = Focus::Sequential,
    a11y:label = "Save",
    on:click = save,
)

A name with no value is shorthand for name = name:

let hidden = true;
box(hidden)             // same as box(hidden = hidden)

A value is any Rust expression, and commas inside it belong to it:

row(state:open = count.get() > 0)
row(x = if a > b { p } else { q })
For(key = |a: &Todo, b: &Todo| a.id > b.id, each = items) { "x" }

Braces around a value are optional: class = {class} and class = class are the same. The one exception is a struct literal, which must be braced so its { is not read as a children block: at = {Point { x, y }}.

Attribute prefixes

A prefix and a colon select the kind of attribute. Attributes documents each one.

row(
    class = "row",                    // the class list
    class:active = on,                // one class, toggled
    style:gap = "1rem",               // one inline style property
    var:--brand = "red",              // a CSS custom property (keep the dashes)
    attr:data-testid = "row",         // an attribute selectors can match
    prop:value = v,                   // a typed property on the element
    state:disabled,                   // a built-in interaction state
    custom_state:picked = p,          // a state of your own
    on:click = handler,               // a listener
    a11y:label = "Save",              // accessibility
    node_ref = handle,                // a handle to the created node
)

Spread a bundle of attributes

{..expr} applies a bundle of attributes at the position where it is written. Attributes before it apply first and attributes after it apply last, so the later one wins.

Button(class:mine = true, {..attrs}, attr:data-x = "1")

A spread belongs in the attribute list. Written among the children, it is a compile error.

Views as values

view! is an expression. Its result implements IntoView, so you can bind it, pass it to a function, and return it.

let header = view! { label(class = "title") {"Storage"} };

view! {
    column {
        {header}
        text {"41 GB"}
    }
}

A view! with several root nodes produces a tuple, and one with none produces (). The roots render as siblings wherever you place them, with no wrapper element.

let two = view! {
    label {"a"}
    label {"b"}
};

A component returns its view, and is then used like any other node:

#[component]
fn Header() -> impl IntoView {
    view! { label(class = "title") {"Storage"} }
}

view! {
    column {
        Header()
        text {"41 GB"}
    }
}

The application's root view comes from the closure passed to run:

fn main() -> Result<(), zgui::Error> {
    app()
        .with_stylesheet(SHEET)
        .run(|| view! { column(class = "app") { text {"Hello"} } })
}

Types you can put in a view

Anything that implements IntoView can be a braced child:

TypeRenders
&'static str, String, Rc<str>one text node, rewritten only when the string changes
bool, char, integers and floatstheir to_string()
()nothing
tuples, up to 26 membersthe members in order, as siblings
Option<V>None renders nothing but keeps its place; Some to Some updates in place
Vec<V>the items, matched by position (see below)
Result<V, E>Ok renders V; Err renders nothing and passes the error to the nearest error boundary
a closure returning a viewa reactive hole that re-runs when what it read changes. See Reactivity in views
an element or component callthat element or component
AnyViewwhatever was erased into it

Vec<V> is positional: it updates the shared prefix in place, builds extra items, and removes the surplus. That suits a fixed set of children. For a collection the user can insert into, remove from or reorder, use for, which is keyed.

Common compile errors

You wroteThe message
spacer`spacer` is a name, not a node
<row/>`<` cannot begin a node
column { 42 }expected a node — write {42}
column { item.label() }`item` is a name, not a node
row() (class = "a")`(` cannot begin a node — the attribute list comes first, once
row(class = "a" hidden)attributes are separated by commas
row(at = Point { x, y })a struct literal in an attribute value goes in braces
Card({attrs})suggests the spread spelling, {..attrs}
while() {}has no meaning in a view — use for and if

Grammar reference

The full view! syntax:

view      = node* ;
node      = text | block | call | flow ;
text      = STRING_LITERAL ;
block     = "{" expression "}" ;
call      = head ( attrs children? | children ) ;
head      = name | path ;
name      = IDENT_ANY segment* ;
segment   = "-" ( IDENT_ANY | INT_LITERAL ) ;
path      = IDENT ( "::" IDENT )+ ;
attrs     = "(" ( attr ( "," attr )* ","? )? ")" ;
children  = "{" node* "}" ;

flow is for and if, covered in Control flow.

Next

On this page