Skip to main content
Version: Next

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.

use yew::prelude::*;

let my_header: Html = html! {
<img src="img_girl.jpg" alt="Girl in a jacket" width="500" height="600" />
};

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

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>
};

html! also accepts any number of root nodes, so you can render a list of multiple elements directly:

use yew::html;

html! {
<div></div>
<p></p>
};

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