條件渲染
If 區塊
要有條件地渲染一些標記,我們將其包裝在 if 區塊中:
- 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 綁定和多子節點
if/else、match 和 for 的大括號主體都支援在 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 遵循相同的模式:
- match
- if 守衛
- let 綁定
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>,
}
};
大括號 arm 主體支援 let 綁定和多個子節點:
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>,
}
};
單元素 arm 可以省略大括號。含多個子節點或 let 綁定的 arm 需要大括號。
match 支援所有標準 Rust 模式,包括 OR 模式(A | B)、解構和 if 守衛。窮舉性由 Rust 編譯器檢查。