Crate html_builder[][src]

Short example:

use html_builder::*;
use std::fmt::Write;

let mut doc = Document::new();                // Contents added to buffer by each statement:
let mut html = doc.html().attr("lang='en'");  // <html lang='en'>
writeln!(html.head().title(), "Title!")?;     // <head><title>Title!
writeln!(html.body().h1(), "Header!")?;       // </title></head><body><h1>Header!
let page = doc.build();                       // </h1></body></html>

Longer example:

use html_builder::*;
use std::fmt::Write;

// Start by creating a Document.  This contains a buffer that we're going
// to be writing into.
let mut doc = Document::new();

// The document is writable
writeln!(doc, "<!-- My website -->")?;

// The Html5 trait provides various helper methods.  For instance, doctype()
// simply writes the <!DOCTYPE> header
doc.doctype();

// Most helper methods create child nodes.  You can set a node's attributes
// like so
let mut html = doc.html().attr("lang='en'");

let mut head = html.head();

// Just like Document, nodes are also writable.  Set their contents by
// writing into them.
writeln!(head.title(), "Website!")?;

// Meta is a "void element", meaning it doesn't need a closing tag.  This is
// handled correctly.
head.meta().attr("charset='utf-8'");

let mut body = html.body();
writeln!(body.h1(), "It's a website!")?;

// Generating HTML in a loop
let mut list = body.ul();
for i in 0..2 {
    writeln!(
        list.li().a().attr(
            &format!("href='/page_{}.html'", i)
        ),
        "Page {}", i,
    )?
}

// You can write functions which add subtrees to a node
fn figure_with_caption(parent: &mut Node, src: &str, cap: &str) {
    let mut fig = parent.figure();
    fig.img()
        .attr(&format!("src='{}'", src))
        .attr(&format!("alt='{}'", cap));
    writeln!(fig.figcaption(), "{}", cap).unwrap();
}

figure_with_caption(&mut body, "img.jpg", "Awesome image");

// Text contents in an inner node
let mut footer = body.footer();
writeln!(footer, "Last modified")?;
writeln!(footer.time(), "2021-04-12")?;

// Finally, call build() to extract the buffer.
let page = doc.build();

assert_eq!(
    page,
    r#"<!-- My website -->
<!DOCTYPE>
<html lang='en'>
 <head>
  <title>
Website!
  </title>
  <meta charset='utf-8'>
 </head>
 <body>
  <h1>
It's a website!
  </h1>
  <ul>
   <li>
    <a href='/page_0.html'>
Page 0
    </a>
   </li>
   <li>
    <a href='/page_1.html'>
Page 1
    </a>
   </li>
  </ul>
  <figure>
   <img src='img.jpg' alt='Awesome image'>
   <figcaption>
Awesome image
   </figcaption>
  </figure>
  <footer>
Last modified
   <time>
2021-04-12
   </time>
  </footer>
 </body>
</html>
"#);

Structs

Document

An HTML document.

Node

An HTML element.

Void

A self-closing element.

Traits

Html5

Helper methods for generating HTML5 documents.