Skip to content

Cannot prepopulate snippet arguments #13610

Closed as not planned
Closed as not planned
@timephy

Description

@timephy

Describe the problem

I have a snippet creating a general element with multiple arguments:

{#snippet item(label: string, icon: IconType, selected: boolean)}
    <button
        onclick={onSelected}
    >
        <Icon data={icon} />
        <p>{label}</p>
        {#if selected}
            <p>(selected)</p>
        {/if}
    </button>
{/snippet}

I wanted to pass different variations of this snippet to a child component, but with prepopulated values for label and icon:

<Child
    elements=[
        (selected: boolean) => item("Home", homeIcon, selected),
        (selected: boolean) => item("Settings", settingsIcon, selected),
    ]
/>

While typing this works great with TypeScript, and svelte-check does not report any errors, a runtime error is thrown:

TypeError: Cannot create property 'out' on string 'Home'
    at item
    at Object.item
    at Module.Parent [as default]
    at _page
    at children
    at Module.slot
    at _layout
    at Root
    at Module.render
    at Function._render [as render]

I Tried this

Neither specifying the prepopulated function/snippet (like above), nor defining a function homeItem(selected: boolean) { ... } in the <script> works.

I guess this is expected, since it seems that snippets are not "simply functions", and are interpreted differently.

I believe that createRawSnippet can not solve this, since it has to return valid HTML (?), and can not return/render a another snippet?

The only solution currenly

The only solution is to create (in this example) two more {#snippet}s for home and settings and pass these to the Child instead of composing the Snippet in-line.


Proposed Solution

I understand that one can not define a snippet inside <script>, as we require the HTML-like syntax of the template, but it would be great if snippets were them "composable" (prepopulate-able) inside JS/TS.

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions