#builder #html #attributes #escaping #another #elements #text

another-html-builder

Yet another html builder, focused on being a helper for creating elements, escaping attributes, escaping text, but not caring if the html structure is valid. It's up to the developer to test that.

5 releases

new 0.2.0 Dec 9, 2024
0.1.3 Nov 30, 2024
0.1.2 Nov 19, 2024
0.1.1 Nov 13, 2024
0.1.0 Nov 11, 2024

#417 in Algorithms

Download history 102/week @ 2024-11-06 251/week @ 2024-11-13 96/week @ 2024-11-20 123/week @ 2024-11-27 86/week @ 2024-12-04

596 downloads per month
Used in git-metrics

MIT/Apache

32KB
689 lines

Another HTML builder

Crates.io

codecov

Average time to resolve an issue Percentage of issues still open

The goal of this builder is to be simple, to only rely on the standard library, to avoid copying values and write directly to a buffer. There is no lock involved, the ownership of the buffer is the only thing that will avoid race conditions.

Example

use another_html_builder::attribute::AttributeValue;
use another_html_builder::prelude::WriterExt;
use another_html_builder::{Body, Buffer};

// define your own custom kind of attributes
enum Lang {
    En,
    Fr,
}

impl AttributeValue for Lang {
    fn render(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            Self::En => "en",
            Self::Fr => "fr",
        })
    }
}

// create custom components
struct Head {
    title: &'static str,
}

impl Default for Head {
    fn default() -> Self {
        Self {
            title: "Hello world!",
        }
    }
}

impl Head {
    fn render<'a, W: WriterExt>(&self, buf: Buffer<W, Body<'a>>) -> Buffer<W, Body<'a>> {
        buf.node("head")
            .content(|buf| buf.node("title").content(|buf| buf.text(self.title)))
    }
}

let head = Head::default();
let html = Buffer::default()
    .doctype()
    .node("html")
    .attr(("lang", Lang::Fr))
    .content(|buf| head.render(buf))
    .into_inner();
assert_eq!(
    html,
    "<!DOCTYPE html><html lang=\"fr\"><head><title>Hello world!</title></head></html>"
);

No runtime deps