Skip to main content

html

Macro html 

Source
html!() { /* proc-macro */ }
Expand description

Generate HTML with maud-like syntax.

The html! macro allows you to write HTML using a maud-like syntax while being as efficient as writing to a String by hand.

§HTML elements

Elements are written using their tag name followed by curly braces containing their children.

html! {
    h1 { "Hello world" }
    p { "This is a paragraph." }
}

Void elements (elements without closing tags) use a trailing semicolon.

html! {
    "First line"
    br;
    "Second line"
}

§Attributes

Attributes are written using name: value.

html! {
    a href: "https://example.com" { "Visit site" }
}

Boolean attributes may omit the value.

html! {
    input r#type: "checkbox" checked;
}

§Shorthand syntax

Instead of writing id and class you may use @ and . respectively.

  • @"container" ==> id: "container"
  • ."flex gap-2" ==> class: "flex gap-2"
html! {
    div @"container" ."flex gap-2" { "content" }
}

§Inserting expressions

Use (expr) to insert any Rust expression implementing Render.

let name = "Alice";

html! {
    p { "Hello " (name) "!" }
}

Expressions that implement Value may be used inside attributes. See its documentation for more details.

let path = "/assets/logo.svg";
let description = "Company logo";

html! {
    img src: (path) alt: (description);
}

§Control structures

§if

let logged_in = true;

html! {
    if logged_in {
        p { "Welcome back!" }
    } else {
        p { "Please log in." }
    }
}

§if let

let name = Some("Damian");

html! {
    if let Some(name) = name {
        (name)
    } else {
       "stranger"
    }
}

§match

let status = 404;

html! {
    match status {
        200 => p { "OK" },
        404 => p { "Not found" },
        _ => p { "Unknown status" }
    }
}

§for

let shows = ["Breaking Bad", "Planet Earth II", "Chernobyl"];

html! {
    h1 { "Popular TV shows" }
    ul {
        for title in shows {
            li { (title) }
        }
    }
}

§let

html! {
    let src = "/assets/welcome.svg";
    img src: (src);

    // You may also provide the type:
    let src: &str = "/assets/welcome.svg";

    // let Some(src) = ... else { ... };
    // ERROR: Only irrefutable patterns are supported
}