HTML with html!

You can write expressions resembling HTML with the html! macro. Behind the scenes Yew turns it into rust code representing the DOM to generate.

  1. use yew::prelude::*;
  2. let my_header: Html = html! {
  3. <img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600" />
  4. };

Similar to format expressions, there is an easy way to embed values from the surrounding context into the html by applying curly brackets:

  1. use yew::prelude::*;
  2. let header_text = "Hello world".to_string();
  3. let header_html: Html = html! {
  4. <h1>{header_text}</h1>
  5. };
  6. let count: usize = 5;
  7. let counter_html: Html = html! {
  8. <p>{"My age is: "}{count}</p>
  9. };
  10. let combined_html: Html = html! {
  11. <div>{header_html}{counter_html}</div>
  12. };

One major rule comes with the use of html! - you can only return 1 wrapping node. To render a list of multiple elements, html! allows fragments. Fragments are tags without a name, that produce no html element by themselves.

  • Invalid
  • Valid
  1. use yew::html;
  2. // error: only one root html element allowed
  3. html! {
  4. <div></div>
  5. <p></p>
  6. };
  1. use yew::html;
  2. // fixed: using html fragments
  3. html! {
  4. <>
  5. <div></div>
  6. <p></p>
  7. </>
  8. };

We will introduce Yew and HTML further in depth in more HTML.