Crate html_builder

source ·
Expand description

Buffer is a magic text buffer that makes writing HTML pleasant.

Here’s a teaser of what it looks like in use:

use html_builder::*;                          // Contents added to buf by each statement
use std::fmt::Write;                          // ---------------------------------------
let mut buf = Buffer::new();                  //
let mut html = buf.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!
buf.finish()                                  // </h1></body></html>

Longer example

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

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

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

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

let mut head = html.head();

// Just like Buffer, 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.

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 1..=3 {
            &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();
        .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")?;

// We also provide a kind of pseudo-node for writing comments
write!(body.comment(), "Thanks for reading")?;

// Finally, call finish() to extract the buffer.
<!DOCTYPE html>
<html lang='en'>
  <meta charset='utf-8'>
  <h1>It's a website!</h1>
   <li><a href='/page_1.html'>Page 1</a></li>
   <li><a href='/page_2.html'>Page 2</a></li>
   <li><a href='/page_3.html'>Page 3</a></li>
   <img src='img.jpg' alt='Awesome image'>
   <figcaption>Awesome image</figcaption>
   Last modified <time>2021-04-12</time>
  <!-- Thanks for reading -->



  • Helper methods for generating HTML5 documents.