Attribute Macro component

Source
#[component]
Available on crate feature alloc only.
Expand description

Convert a function returning a Renderable into a component.

This is a procedural macro that takes a function and generates a struct that holds the function’s parameters. The struct implements Renderable and can be used as a component.

There are three types of parameters that are supported:

  • T: Stored as T in the struct, and will use Copy to provide the value to the function.
  • &T: Stored as T in the struct, and will borrow the value from the struct when calling the function.
  • &'a T: Stored as &'a T in the struct, useful for borrowing unsized types such as str or [T] without needing to convert them to their owned counterparts.

The name of the generated struct is derived from the function name by converting it to PascalCase. If you would like to set a different name, you can specify it as #[component(MyComponentName)] on the function.

The visibility of the generated struct is determined by the visibility of the function. If you would like to set a different visibility, you can specify it as #[component(pub)], #[component(pub(crate))], etc. on the function.

You can combine both of these by setting an attribute like #[component(pub MyComponentName)].

§Example

use hypertext::prelude::*;

#[component]
fn nav_bar<'a>(title: &'a str, subtitle: &String) -> impl Renderable {
    maud! {
        nav {
            h1 { (title) }
            h2 { (subtitle) }
        }
    }
}

assert_eq!(
    maud! {
         div {
             NavBar title="My Nav Bar" subtitle=("My Subtitle".to_owned());
         }
    }
    .render()
    .as_inner(),
    "<div><nav><h1>My Nav Bar</h1><h2>My Subtitle</h2></nav></div>",
);