Conditional rendering
If blocks
To conditionally render some markup, we wrap it in an if block:
- if
- if - else
- if let
- if let else
use yew::prelude::*;
html! {
if true {
<p>{ "True case" }</p>
}
};
use yew::prelude::*;
let some_condition = true;
html! {
if some_condition {
<p>{ "True case" }</p>
} else {
<p>{ "False case" }</p>
}
};
use yew::prelude::*;
let some_text = Some("text");
html! {
if let Some(text) = some_text {
<p>{ text }</p>
}
};
use yew::prelude::*;
let some_text = Some("text");
html! {
if let Some(text) = some_text {
<p>{ text }</p>
} else {
<p>{ "False 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:
- match
- If guards
- Let bindings
use yew::prelude::*;
let value: Option<String> = Some("hello".into());
html! {
match value {
Some(text) => <p>{text}</p>,
None => <p>{"Nothing here"}</p>,
}
};
use yew::prelude::*;
let value: i32 = 42;
html! {
match value {
x if x > 10 => <p>{"Big"}</p>,
x if x > 0 => <p>{"Small"}</p>,
_ => <p>{"Non-positive"}</p>,
}
};
Braced arm bodies support let bindings and multiple children:
use yew::prelude::*;
html! {
match data {
Some(item) => {
let label = format!("Item: {}", item.name);
let class = if item.important { "highlight" } else { "normal" };
<p class={class}>{label}</p>
}
None => <p>{"No data"}</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.