html! is a declarative macro for generating HTML directly inside your Rust
project. It expands at compile time to code that creates a String with html
tags.
Rust code can be used inside <rust> blocks and markup emitted from Rust is
wrapped in <markup>.
Use <include /> to insert HTML content from another component.
use kaja_html_macro::html;
fn parent() -> String {
let content = html! {{
<section>
<include child_component_simple_loop() />
</section>
}};
content
}
fn child_component_simple_loop() -> String {
let content = html! {{
<h1>Hello From Nested Component</h1>
<ul>
<rust>
for i in 1..=3 {
let element_id = format!("list item {:?}", i);
<markup>
<li>Simple $element_id</li>
</markup>
}
</rust>
</ul>
}};
content
}<section>
<h1>Hello From Nested Component</h1>
<ul>
<li>Simple list item 1</li>
<li>Simple list item 2</li>
<li>Simple list item 3</li>
</ul>
</section>$variable_name– insert content of the variable and escape tags.$(get_value())– insert string from the get_value function and escape tags.$(x + 2)– compute x + 2 and add the content to the html string, escaped if needed.<include some_other_component() />– insert trusted HTML content from the function some_other_component, html tags are allowed.
- Write HTML-like markup directly in Rust
- Embed Rust control flow with
<rust>, plain Rust code, no domain specific language - Emit markup dynamically using
<markup> - Interpolate variables and expressions
- Returns a
String
Inserts a variable and escapes HTML tags.
use kaja_html_macro::html;
let name = "<b>Johan</b>";
let html = html! {{
<p>Hello $name</p>
}};Output:
<p>Hello <b>Johan</b></p>You can evaluate arbitrary Rust expressions:
- Function calls
- Arithmetic
- Method calls
- Complex expressions
Expressions are also automatically escaped.
use kaja_html_macro::html;
fn get_value() -> String {
"42".to_string()
}
let test = 5;
let html = html! {{
<div>
<p>Value: $(get_value())</p>
<p>Next: $(test + 1)</p>
</div>
}};use kaja_html_macro::html;
struct TestInfo {
id: u64,
}
let info = TestInfo {
id: 42,
};
let html = html! {{
<div>
<p>ID: $(info.id)</p>
</div>
}};- Written by Johan Mattsson
- johan.mattsson.m@gmail.com
- https://kajacode.com