#html #html-generator #flexibly

htmlbuilder

Build html flexibly and easily in Rust

5 releases (1 stable)

Uses new Rust 2024

new 1.0.0 Feb 24, 2026
0.4.0 Feb 11, 2026
0.3.0 Feb 9, 2026
0.2.0 Feb 8, 2026
0.1.0 Feb 8, 2026

#2 in #html-generator

MIT license

17KB
340 lines

htmlbuilder

A flexible html generator for rust.

create an Element

use htmlbuilder::Element

let root = Element::new("html", "");
let result = root.render("\n");

create with attributes

let body = Element::new("body", "");
let div = Element::new("div", "");
// use clone because div is used later
body.add(div.clone());
// set attributes for div
div.set_attrs(&[("id", "main"), ("class", "container<>")]);

Element is Rc<RefCell<...>> exactly.

For more usage methods, please refer to the documentation.

A complex example

use htmlbuilder::Element

fn main() {
    let root = Element::new("html", "");

    let head = Element::new("head", "")
        .add_with(Element::new("title", "My Page"))
        .add_with(
            Element::new("meta", "").ontag(true)
                .kws(HashMap::from([("charset", "utf-8".to_string())]))
            );
    root.add(head);

    let body = Element::new("body", "");
    root.add(body.clone());

    let div = Element::new("div", "");
    body.add(div.clone());
    let mut attrs = HashMap::new();
    attrs.insert("id", "main".to_string());
    attrs.insert("class", "container<>".to_string());
	// configkws uses HashMap to replace all attributes
    div.configkws(attrs);
    div.configcnt("&<html><div>content&");

    // print parent element
    if let Some(parent) = div.parent() {
        println!("{}", parent.render("\n"));
    }

    div.add(Element::new("h1", "rusthtmlbuilder"));

    // append <ul>
    let ul = Element::new("ul", "");
    div.add(ul.clone());

    for i in 0..10 {
        ul.add(Element::new("li", &i.to_string()));
    }

    // Delete the penultimate li
    {
        let children_count = ul.children().len();
        if children_count >= 2 {
            ul.remove_child(children_count - 2);
        }
    }

    div.add(Element::new("", "content with blank tag name"));

    let result = root.render("\n");
    println!("{}", result);
}

The final output:

<html>
<head>
<title>My Page</title>
<meta charset="utf-8"/>
</head>
<body>
<div class="container&lt;&gt;" id="main">&amp;&lt;html&gt;&lt;div&gt;content&amp;
<h1>rusthtmlbuilder</h1>
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>9</li>
</ul>
content with blank tag name
</div>
</body>
</html>

No runtime deps