chinedufn / percy

Build frontend browser apps with Rust + WebAssembly. Supports server side rendering.
https://chinedufn.github.io/percy/
Apache License 2.0
2.26k stars 84 forks source link

Single branch if statement in html! macro #136

Closed rickihastings closed 4 years ago

rickihastings commented 4 years ago

This PR adds single branch if statement capabilities into the html! macro, which is a very common use case in React-like frameworks (generally achieved with condition && <jsx/>. See an example below:

html! {
    <div>
        <h1>A component</h1>
        {if some_condition_is_true {
            html! { <span>Child</span> }
        }}
    </div>
}

Currently to do this sort of thing is quite clunky, as if statements are expressions in rust you have to do something like the following which really bloats the components.

let child = if some_condition_is_true {
    html! { <span>Child</span> }
} else {
    html! { "" }
};

html! {
    <div>
        <h1>A component</h1>
        {child}
    </div>
}

I appreciate this is slightly against the grain of rust as you can't do this in traditional rust code however I think it makes sense to include this functionality inside the html! macro.

I've added some unit tests for if, else and single branch if statements. I'm pretty new to rust so please let me know if you think anything could be done better. I can also add examples if required, but seems like the tests might cover that.

rickihastings commented 4 years ago

Thanks for the feedback! The improvement to push_iterable_nodes is definitely more idiomatic.

I'll get these changes made soon when I get a chance.

chinedufn commented 4 years ago

Nice!