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 編譯器檢查。