Skip to main content
Version: Next

Conditional rendering

If blocks

To conditionally render some markup, we wrap it in an if block:

use yew::prelude::*;

html! {
if true {
<p>{ "True case" }</p>
}
};

Let bindings and multiple children

Braced bodies in if/else, match, and for all support let bindings before html children, as well as multiple children without a fragment wrapper:

use yew::prelude::*;

html! {
if condition {
let label = format!("count: {count}");
<h2>{"Result"}</h2>
<span>{label}</span>
} else {
"nothing"
}
};

let bindings must appear before any html children and cannot be interleaved with them.

Match blocks

match expressions work directly in html!, following the same pattern as if/else:

use yew::prelude::*;

let value: Option<String> = Some("hello".into());

html! {
match value {
Some(text) => <p>{text}</p>,
None => <p>{"Nothing here"}</p>,
}
};

Arms with a single element can omit braces. Arms with multiple children or let bindings require braces.

match supports all standard Rust patterns including OR-patterns (A | B), destructuring, and if guards. Exhaustiveness is checked by the Rust compiler.