Write HTML as Rust data structures https://crates.io/crates/el
Find a file
Joscha abd0cc6247 Add Attr::set
The name "set" makes more sense compared to "append" than "new". "new"
only exists because originally there was no "append".
2024-12-14 12:37:46 +01:00
.vscode Switch from axum to axum-core and http 2024-12-02 21:11:59 +01:00
src Add Attr::set 2024-12-14 12:37:46 +01:00
.gitignore Add axum support 2024-11-27 00:26:26 +01:00
Cargo.toml Bump version to 0.1.1 2024-12-08 00:24:39 +01:00
CHANGELOG.md Add Attr::set 2024-12-14 12:37:46 +01:00
LICENSE-APACHE Add licenses and crate info 2024-12-02 18:14:37 +01:00
LICENSE-MIT Add licenses and crate info 2024-12-02 18:14:37 +01:00
README.md Tweak readme and lib docs 2024-12-08 00:20:51 +01:00

el

el is a no-dependencies Rust library for writing, modifying, and safely rendering HTML elements as simple data structures. It is inspired by hiccup and named after a small helper function I once wrote in JS.

Show me a simple example

use el::{Attr, Render, html::*};

let page: String = html((
    head((
        meta(Attr::new("charset", "utf-8")),
        meta((
            Attr::new("name", "viewport"),
            Attr::new("content", "width=device-width, initial-scale=1"),
        )),
        title("Example page"),
    )),
    body((
        h1((Attr::id("heading"), "Example page")),
        p(("This is an example for a ", em("simple"), " web page.")),
    )),
))
.into_document()
.render_to_string()
.unwrap();

What now?

See the top-level crate documentation for more info.

But what about that small helper function?

Here it is in full, for posteriority:

function el(name, attributes, ...children) {
  const element = document.createElement(name);
  for (const [name, value] of Object.entries(attributes))
    element.setAttribute(name, value);
  element.append(...children);
  return element;
}

Use it like so:

const page = el("html", {},
  el("head", {},
    el("meta", { charset: "utf-8" }),
    el("meta", {
        name: "viewport",
        content: "width=device-width, initial-scale=1",
    }),
    el("title", {}, "Example page")
  ),
  el("body", {},
    el("h1", { id: "heading" }, "Example page"),
    el("p", {}, "This is an example for a ", el("em", {}, "simple"), " web page."),
  ),
);

License

This entire project is dual-licensed under the Apache 2.0 and MIT licenses.