Macro element

Source
macro_rules! element {
    ($vis:vis $ElementName:ident $(($name:literal))? $([$AttributeName:ident])? $({ $($attribute:ident $(: $atype:ty)?),* $(,)? })?) => { ... };
    (@NAME_STR $ElementName:ident) => { ... };
    (@NAME_STR $ElementName:ident($name:literal)) => { ... };
}
Available on crate feature typed only.
Expand description

Make a typed element.

§Examples

§Fully Generated (With Custom Name)

use html_node::typed;

typed::element! {
    CustomElement("custom-element") {
        custom_attr,
    }
}

// note that global attributes like `id` will be pre-defined when
// using the `typed::element!` macro.
assert_eq!(
    typed::html!(<CustomElement id="el" custom-attr="test" />).to_string(),
    r#"<custom-element id="el" custom-attr="test"></custom-element>"#,
);

§Fully Generated (With Default Name)

use html_node::typed;

typed::element! {
    CustomElement {
        custom_attr,
    }
}

assert_eq!(
    typed::html!(<CustomElement id="el" custom-attr="test" />).to_string(),
    r#"<CustomElement id="el" custom-attr="test"></CustomElement>"#,
);

§Generated With Custom Attributes Name

use html_node::typed::{self, TypedAttributes};

typed::element! {
    CustomElement [CustomElementAttributesDifferent] {
        custom_attr,
    }
}

assert_eq!(
    typed::html!(<CustomElement id="el" custom-attr="test" />).to_string(),
    r#"<CustomElement id="el" custom-attr="test"></CustomElement>"#,
);

§Generated With Custom Attributes

use html_node::typed::{self, Attribute, TypedAttributes};

#[derive(Debug, Clone, Default)]
struct CustomElementAttributes {
    custom_attr: Attribute<String>,
}

impl TypedAttributes for CustomElementAttributes {
    fn into_attributes(self) -> Vec<(String, Option<String>)> {
        vec![self.custom_attr.into_option().map(|v| ("custom-attr".into(), v))]
            .into_iter()
            .flatten()
            .collect()
    }
}

typed::element! {
    CustomElement [CustomElementAttributes]
}

// note that global attributes like `id` will not be allowed here
// because they are not defined in `CustomElementAttributes`.
assert_eq!(
    typed::html!(<CustomElement custom-attr="test" />).to_string(),
    r#"<CustomElement custom-attr="test"></CustomElement>"#,
);