This is unreleased documentation for Yew Next version.
For up-to-date documentation, see the latest version on docs.rs.
yew::macros

Macro html_nested

source
html_nested!() { /* proc-macro */ }
Expand description

This macro is similar to html!, but preserves the component type instead of wrapping it in Html.

That macro is useful when, for example, in a typical implementation of a list component (let’s assume it’s called List). In a typical implementation you might find two component types – List and ListItem. Only ListItem components are allowed to be children of List`.

You can find an example implementation of this in the nested_list example. That example shows, how to create static lists with their children.

use yew::html::ChildrenRenderer;
use yew::virtual_dom::VChild;

#[derive(Clone, Properties, PartialEq)]
struct ListProps {
    children: ChildrenRenderer<ListItem>,
}

struct List;
impl Component for List {
    type Properties = ListProps;
    // ...
}

#[derive(Clone, PartialEq)]
struct ListItem;
impl Component for ListItem {
    // ...
}

// Required for ChildrenRenderer
impl From<VChild<ListItem>> for ListItem {
    fn from(child: VChild<ListItem>) -> Self {
        Self
    }
}

impl Into<Html> for ListItem {
    fn into(self) -> Html {
        html! { <self /> }
    }
}
// You can use `List` with nested `ListItem` components.
// Using any other kind of element would result in a compile error.
html! {
  <List>
    <ListItem/>
    <ListItem/>
    <ListItem/>
  </List>
}
// In many cases you might want to create the content dynamically.
// To do this, you can use the following code:
html! {
  <List>
    { for some_iter.map(|_| html_nested!{ <ListItem/> }) }
  </List>
}

If you used the html! macro instead of html_nested!, the code would not compile because we explicitly indicated to the compiler that List can only contain elements of type ListItem using ChildrenRenderer<ListItem>, while html! creates items of type Html.