html

Macro html 

Source
macro_rules! html {
    ($($input:tt)*) => { ... };
}
Expand description

This macro implements a syntax for creating HTML Nodes.

ยงSyntax

A lone identifier represents an HTML element:

let html = toph::html! {
        div
};
assert_eq!(html.to_string(), "<div></div>");

Elements can have attributes. These are expressed as a key-value list seperated by commas.

The key must be a valid rust identifier. The value must implement Display. Since dashes are not valid identifiers, underscores in attribute names are converted to dashes.

Double quotes in attribute values are escaped.

let html = toph::html! {
    div[data_count = "y\"all", id ="main"]
};
assert_eq!(
    html.to_string(),
    "<div data-count=\"y&quot;all\" id=\"main\"></div>"
);

As a special case, the data-tagname attribute can be used to override the name of the html tag. This is useful when the tag name is determined at runtime:

let tagname = "div";
let html = toph::html! {
    thiscanbeanything[data_tagname = tagname]
};
assert_eq!(
    html.to_string(),
    "<div data-tagname=\"div\"></div>"
)

HTML boolean attribute can be expressed as &'static str expressions.

let async_attr = if true { "" } else { "async" };
let readonly_attr = if true { "readonly" } else { "" };
let html = toph::html! {
    div [readonly_attr , async_attr, "other"]
};
assert_eq!(
    html.to_string(),
    "<div readonly other></div>"
);

Elements can have children:

let html = toph::html! {
    div {
        span { p }
    }
};
assert_eq!(
    html.to_string(),
    "<div><span><p></p></span></div>"
);

Insert HTML-escaped text with text(). Insert raw, unescaped text with raw_text(). Anything that implements Display can be passed as an argument.

Text must be surrounded by parentheses.

let html = toph::html! {
    div[class = "\""] {
        (toph::text("<span>"))
        (toph::raw_text("<span>"))
    }
};
assert_eq!(
    html.to_string(),
    "<div class=\"&quot;\">&lt;span&gt;<span></div>"
);

Lastly, the child of an HTML element may also be any Rust expression that returns one or more Nodes.

More specifically, in addition to expressions returning a single Node, any expression whose return value implements IntoIterator<Item = Node> qualifies. Among other things, this means you can use:

  • Result<Node, E>
  • Option<Node>,
  • Any iterator that yields Nodes
  • An array or Vec of Nodes.

Expressions must also be surrounded by parentheses.

let option = Some(toph::html!{ (toph::text("option")) });
let iterator = (0..=2).into_iter().map(|n| toph::html! { (toph::text(n)) });
let html = toph::html! {
    div {
        (option)
        (iterator)
    }
};
assert_eq!(
    html.to_string(),
    "<div>option012</div>"
);