Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
martinhath opened this issue Oct 9, 2024 · 3 comments
Open

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

martinhath opened this issue Oct 9, 2024 · 3 comments

Comments

@martinhath
Copy link

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.

@re-oh
Copy link

re-oh commented Oct 10, 2024

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

@re-oh
Copy link

re-oh commented Oct 10, 2024

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.

@Porges
Copy link

Porges commented Dec 20, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants