render-rs / render.rs

🔏 A safe and simple template engine with the ergonomics of JSX
https://docs.rs/render
MIT License
238 stars 23 forks source link

rsx!() None #14

Closed theashguy closed 4 years ago

theashguy commented 4 years ago

Another thing I've found in my playing has been that if you're rendering template vars with branches inside them, and want to show something conditionally you often need to return some kind of marker of the same type as is produced by rsx, but that results in a null render.

A trivial example...

rsx!(
  <div>
    {match some_boolean {
      true => rsx!(<p>That is a thing</p>),
      _ => rsx!() / None / ""
    }}
  </div>
)

I've tried a range of different options to produce a null result including rsx!(), rsx!(<></>), None etc but they're all guarded against inside the macro or the wrong type (None was a hail mary I grant you).

To get around this I'm forced to render my template inside the branch (I just use html!() for brevity), and return an empty string for the other branch, which works fine, but I suspect isn't performant nor elegant.

Is there an idiomatic way to do this in the library today?

daaku commented 4 years ago

I'll send a pull request with this test soon, but it can be done like so:

#[test]
fn some_none() {
    use pretty_assertions::assert_eq;
    use render::{component, html, rsx};

    #[component]
    fn Answer(a: i8) {
        rsx! {
          <>
            {match a {
              42 => Some("Yes"),
              _ => None,
            }}
          </>
        }
    }

    assert_eq!(html! { <Answer a={42} /> }, "Yes");
    assert_eq!(html! { <Answer a={44} /> }, "");
}