rhtml!() { /* proc-macro */ }Expand description
rust_html - The minimal Rust HTML templating library
The rhtml macro enables you to easily create composable HTML templates by
injecting any identifier, expression or literal that implements
the standard std::fmt::Display trait. The macro protects against
injection attacks and validates the HTML syntax in compile time.
§Examples
Simple example with injected value:
use rust_html::rhtml;
let value = "Hello, World";
let page = rhtml! { "<span>{value}</span>" };
assert_eq!(&String::from(page), "<span>Hello, World</span>");Example with reusable component:
use rust_html::rhtml;
let card = |title: &str| {
rhtml! { r#"<div class="card">{title}</div>"# }
};
let page = rhtml! { r#"
<div class="container">
{card("Card A")}
{card("Card B")}
</div>
"#};
assert_eq!(
&String::from(page), r#"
<div class="container">
<div class="card">Card A</div>
<div class="card">Card B</div>
</div>
"#);Runtime rust-values are escaped by default to protect against injection attacks:
use rust_html::rhtml;
let value = "<script>";
let page = rhtml! { "<span>{value}</span>" };
assert_eq!(&String::from(page), "<span><script></span>");You can use raw/unescaped values with the Unescaped
wrapper, but never do this with untrusted user input!
Unescaped will also break the compile-time guarantee of
valid HTML syntax in your template.
use rust_html::{rhtml, Unescaped};
let value = Unescaped("<script>".to_string());
let page = rhtml! { "<span>{value}</span>" };
assert_eq!(&String::from(page), "<span><script></span>");The macro does compile time syntax checking of your HTML. The following example will not compile due to missing quotes around the class name:
use rust_html::rhtml;
let class = "red";
let page = rhtml! { "<div class={class}></div>" };
assert_eq!(String::from(page), "<div class=my_class></div>");For more examples and documentation, check out the README.md