Skip to main content
Version: Next

條件渲染

If 區塊

要有條件地渲染一些標記,我們將其包裝在 if 區塊中:

use yew::prelude::*;

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

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