Crate fun_html

Source
Expand description

This crate provides a simple and efficient way to generate HTML using Rust functions, with an intuitive and composable API to create HTML elements.

The elt module contains functions to create common HTML elements. Most of them take 2 arguments: The list of attributes, and the list of children. For example, div([id("mydiv")], ["hello".into()]) creates a <div> with an ID of “mydiv” containing the text “hello”.

The attr module contains functions to create common attributes.

Text can be inserted by using the elt::text function or by using one of the Into<Element> implementations. All text and attribute values are automatically escaped to ensure safe and valid HTML output.

use fun_html::{attr, elt};

let greeting = elt::h1(
  [attr::class(["bold"])], // <-- attributes
  ["Hello world!".into()], // <-- children
);
assert_eq!(greeting.to_string(), r#"<h1 class="bold">Hello world!</h1>"#);

Because those are simple rust functions, it is easy to leverage rust features like conditions, loops and iterators:

use fun_html::{elt, Element};

fn list_view(items: Vec<i32>) -> Element {
  if !items.is_empty(){
    elt::ul([], items.into_iter().map(|item| elt::li([], [item.to_string().into()])))
  } else {
    elt::text("no item")
  }
};

assert_eq!(
  list_view((1..=3).collect()).to_string(),
  "<ul><li>1</li><li>2</li><li>3</li></ul>"
);

§Escape hatches

If necessary, it is possible to define custom elements and attributes with respectively Element::new and Attribute::new.

It is also possible to declare custom attributes on the fly like this: div([("hx-get", "/values").into()], []))

It is also possible to inline raw html with:

  • elt::raw: inline HTML that is known at compile time, and is therefore considered safe.
  • elt::raw_unsafe: can inline HTML built at runtime, and is therefore unsafe.

§Feature flags

Modules§

attr
Common attributes
elt
Common HTML elements

Structs§

Attribute
An attribute
Document
An HTML document (<!DOCTYPE html>)
Element
An HTML element

Functions§

html
Create an HTML Document