mirror of
https://github.com/yewstack/yew.git
synced 2025-12-08 21:26:25 +00:00
* Docs overhaul part2 * fix links and require them for CI * remove translations for 0.17 * remove a bunch of unused documentation * run prettier * fixup links and locations of some translations
89 lines
2.0 KiB
Plaintext
89 lines
2.0 KiB
Plaintext
---
|
|
title: 'HTML with html!'
|
|
description: 'Its HTML but not quite!'
|
|
comment: 'Keep this file as short and simple as possible. Its purpose is to ease in the reader into components in Yew instead of providing proper API docs'
|
|
---
|
|
|
|
import Tabs from '@theme/Tabs'
|
|
import TabItem from '@theme/TabItem'
|
|
|
|
> Yew mostly operates on the idea of keeping everything that a reusable piece of
|
|
> UI may need, in one place - rust files. But also seeks to stay close to the
|
|
> original look of the technology.
|
|
|
|
For HTML we achieve this by providing the `html!` macro:
|
|
|
|
```rust
|
|
use yew::prelude::*;
|
|
|
|
let my_header: Html = html!{<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600" />};
|
|
```
|
|
|
|
`html!` macro allows you to write html generation as if it was in a `.html` file and then behind the scenes by yew gets turned into internal builder patterns that generate all DOM nodes.
|
|
|
|
As it is part of rust code it provides a easy way to switch from html to rust by applying curly brackets:
|
|
|
|
```rust
|
|
use yew::prelude::*;
|
|
|
|
let header_text = "Hello world".to_string();
|
|
let header_html: Html = html!{<h1>{header_text}</h1>};
|
|
|
|
let count: usize = 5;
|
|
let counter_html: Html = html!{<p>{"My age is: "}{count}</p>};
|
|
|
|
let combined_html: Html = html!{<div>{header_html}{counter_html}</div>};
|
|
```
|
|
|
|
One rule major rule comes with use of `html!` - you can only return 1 wrapping node:
|
|
|
|
<Tabs>
|
|
<TabItem value="Valid" label="Valid">
|
|
|
|
```rust
|
|
use yew::html;
|
|
|
|
html! {
|
|
<div>
|
|
<div></div>
|
|
<p></p>
|
|
</div>
|
|
};
|
|
|
|
```
|
|
|
|
</TabItem>
|
|
|
|
<TabItem value="Invalid" label="Invalid">
|
|
|
|
```rust, compile_fail
|
|
use yew::html;
|
|
|
|
// error: only one root html element allowed
|
|
|
|
html! {
|
|
<div></div>
|
|
<p></p>
|
|
};
|
|
|
|
```
|
|
|
|
</TabItem>
|
|
</Tabs>
|
|
|
|
To help with this rule and avoid `div` abuse `html!` allows fragments. Fragments are empty tags that do not provide any html result:
|
|
|
|
```rust
|
|
use yew::html;
|
|
|
|
html! {
|
|
<>
|
|
<div></div>
|
|
<p></p>
|
|
</>
|
|
};
|
|
|
|
```
|
|
|
|
We will introduce Yew and HTML further in depth in [more HTML](concepts/html/introduction.mdx).
|