sycamore icon indicating copy to clipboard operation
sycamore copied to clipboard

Optional attributes in view!

Open smessmer opened this issue 2 years ago • 0 comments

It would be great if the view! macro allowed attributes to be set to an Optional, and then would generate the attribute if and only if the Optional is Some.

Use case: Let's say we are wrapping a input component into our own Switch component:


#[derive(Prop)]
pub struct SwitchProps<'cx> {
    checked: &'cx Signal<bool>,
    // id can be present or absent
    #[builder(default)]
    id: Option<&'cx str>,
}

#[component]
pub fn Switch<'a, G: Html>(cx: Scope<'a>, props: SwitchProps<'a>) -> View<G> {
    view! {cx,
        input(
            type="checkbox",
            role="switch",
            class="...",
            id=(props.id),
            bind:checked=props.checked,
        )
    }
}

The SwitchProps::id prop will be present or absent depending on whether the call site specified it. But the view! macro currently does not allow it being passed through to input the same way. Instead, we have to write much more verbosely:

#[component]
pub fn Switch<'a, G: Html>(cx: Scope<'a>, props: SwitchProps<'a>) -> View<G> {
    if let Some(id) = props.id {
        view! {cx,
            input(
                type="checkbox",
                role="switch",
                class="...",
                id=id,
                bind:checked=props.checked,
            )
        }
    } else {
        view! {cx,
            input(
                type="checkbox",
                role="switch",
                class="...",
                bind:checked=props.checked,
            )
        }
    }
}

smessmer avatar Sep 02 '23 18:09 smessmer