#generate-html #html #web #html-string #javascript

htmlify

Trait used to generate HTML from Rust structures

10 stable releases

1.3.0 Jan 28, 2024
1.2.2 Oct 25, 2021

#933 in WebAssembly

Download history 3/week @ 2024-01-25 4/week @ 2024-02-01 2/week @ 2024-02-15 11/week @ 2024-02-22 6/week @ 2024-02-29 5/week @ 2024-03-07 3/week @ 2024-03-14 35/week @ 2024-03-28 14/week @ 2024-04-04

64 downloads per month
Used in aframe

MIT/Apache

10KB
144 lines

Trait used to generate HTML from Rust structures

It contains the following optional definitions:

// Defaults to an empty string
fn tag(&self) -> Cow<'static, str> { /* ... */ }
// Defaults to empty vec
fn attributes(&self) -> Vec<Attribute> { /* ... */ }
// Defaults to empty vec
fn inner_html(&self) -> Vec<Box<dyn Htmlify>> { /* ... */ }

The following method should not need to be implemented:

// Calls `as_raw_html` for each of the items returned by `inner_html`
fn inner_html_as_string(&self) -> String { /* ... */ }

The following definition also should not need to be implemented, but may on occasion be useful to override:

fn as_raw_html(&self) -> String 
{
    format!
    (
        "<{0} {2}> {1} </{0}>",
        self.tag(),
        self.inner_html_as_string(),
        self.attributes()
            .iter()
            .map(Attribute::to_string)
            .collect::<Vec<String>>()
            .join(" ")
    )
}

The web-sys feature may be enabled to allow access to the following default function:

fn as_element(&self) -> Option<web_sys::Element> { /* ... */ }

The yew feature may be enabled to allow access to the following default function:

fn as_yew_node(&self) -> Html { /* ... */ }

There are 3 other tools included in this crate:

  • An Htmlify implementation for &str. This is a special case which simply returns the string itself when as_raw_html is called, and returns None when as_element is called. This is so text-content "leaves" can be represented. (and the default implementation of as_element understands this).
  • An Attribute struct to store key-value pairs as strings, used specifically for element attributes. These use Cow<'static, str> to leave optimization details up to the implementor.
  • The web-sys feature also provides access to an append_to_document_body function which takes any impl Htmlify and attempts to append it to the document body (through web_sys calls). This is here purely for convenience.

Dependencies

~0–3.5MB
~67K SLoC