Skip to content

Consider using iterator extensions to make the writing of map expressions more concise #10

Closed
@cameronbraid

Description

Your simple example has :

#[component]
async fn Items() -> String {
    let data = load_data_async().await;
    html! {
        <ul>
            {
                data
                    .into_iter()
                    .map(|item| html! { <li>{ item }</li> })
                    .collect_fragment() // helper method to collect a list of components into a String
            }
        </ul>
    }
}

I propose to provide a map_fragment iterator extension that lets you write the following :

#[component]
async fn Items() -> String {
    let data = load_data_async().await;
    html! {
        <ul>
            {
                data
                    .into_iter()
                    .map_fragment(|item| html! { <li>{ item }</li> })
            }
        </ul>
    }
}

Its pretty straight forward :

pub trait MapFragmentExt: Iterator {
    fn map_fragment<F, B>(self, f: F) -> String
    where
        Self: Sized,
        F: FnMut(Self::Item) -> B,
        B: ToString;
}

impl<T> MapFragmentExt for T
where
    T: Iterator,
{
    fn map_fragment<F, B>(self, f: F) -> String
    where
        Self: Sized,
        F: FnMut(Self::Item) -> B,
        B: ToString,
    {
        self.map(f).map(|b| b.to_string()).collect::<Vec<_>>().join("")
    }
}

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions