yew/website/i18n/ja/docusaurus-plugin-content-docs/current/concepts/html/literals-and-expressions.mdx

72 lines
1.7 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 'リテラルと式'
---
## リテラル
式が `Display` を実装する型に解決される場合、それらは文字列に変換され、[Text](https://developer.mozilla.org/en-US/docs/Web/API/Text) ードとしてDOMに挿入されます。
:::note
文字列リテラルは `Text` ノードを作成し、ブラウザはそれを文字列として扱います。そのため、式に `<script>` タグが含まれていても、式を `<script>` ブロックでラップしない限り、XSS などのセキュリティ問題に遭遇することはありません。
:::
すべての表示テキストは式と見なされるため、`{}` ブロックで囲む必要があります。これは、Yew と通常の HTML 構文の最大の違いです。
```rust
use yew::prelude::*;
let text = "lorem ipsum";
html!{
<>
<div>{text}</div>
<div>{"dolor sit"}</div>
<span>{42}</span>
</>
};
```
## 式
`{}` ブロックを使用して、HTML 内に式を挿入できます。それらが `Html` に解決される限り。
```rust
use yew::prelude::*;
let show_link = true;
html! {
<div>
{
if show_link {
html! {
<a href="https://example.com">{"Link"}</a>
}
} else {
html! {}
}
}
</div>
};
```
通常、これらの式を関数やクロージャに抽出して、可読性を最適化することが意味があります:
```rust
use yew::prelude::*;
let show_link = true;
let maybe_display_link = move || -> Html {
if show_link {
html! {
<a href="https://example.com">{"Link"}</a>
}
} else {
html! {}
}
};
html! {
<div>{maybe_display_link()}</div>
};
```