maud icon indicating copy to clipboard operation
maud copied to clipboard

impl Render<T: Render> for Option<T>

Open martinhath opened this issue 1 year ago • 3 comments
trafficstars

Thanks for a nice library!

I ran into a case where I want to conditionally insert some markup, the condition being on an Option. Ended up writing

html! {
    @if let Some(n) = foo() { (n) }
}

but it would have been cool if

html! {
    (foo())
}

worked, and behaved identically.

martinhath avatar Oct 09 '24 20:10 martinhath

Ill attempt to fix this, want to contribute since this is a really cool lib.

re-oh avatar Oct 10 '24 10:10 re-oh

impl<T: Render + ?Sized> Render for Option<T> {
    fn render_to(&self, w: &mut String) { if let Some(inner) = self { T::render_to(inner, w); } }
}

impl <T: Render + ?Sized, I: ExactSizeIterator + ?Sized> Render for I where I::Item: AsRef<T> {
    fn render_to(&self, w: &mut String) {
        for item in self {
            item.as_ref().render_to(w);
        }
    }
}

Implemented Render for 2 types:

  • ExactSizeIterator since if it was infinite like: 0.. it would run forever. ( Not sure if this implementation works, if anyone could tell me how i can test this it would be much appreciated since you dont need a owned value to render it. ergo AsRef<T> for I::Item)
  • Option<T> Simple, if self is some render the inner value if not, dont render it. ( I think thats how @martinhath wanted it to work. )

If there are any suggestions for other types to implement or if my implementation has issues ill gladly fix them.

re-oh avatar Oct 10 '24 11:10 re-oh

This would be nice, it’s similar to how both null/false skip rendering in React.

Porges avatar Dec 20 '24 01:12 Porges