Skip to main content
Version: Next

条件渲染

If 块

要有条件地渲染一些标记,我们将其包装在 if 块中:

use yew::prelude::*;

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

let 绑定和多子节点

if/elsematchfor 的大括号体都支持在 html 子节点前使用 let 绑定,以及无需片段包装的多个子节点:

use yew::prelude::*;

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

let 绑定必须出现在所有 html 子节点之前,不能与它们交错。

Match 块

match 表达式可以直接在 html! 中使用,与 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>,
}
};

单元素 arm 可以省略大括号。含多个子节点或 let 绑定的 arm 需要大括号。

match 支持所有标准 Rust 模式,包括 OR 模式(A | B)、解构和 if 守卫。穷尽性由 Rust 编译器检查。