Skip to content

Switch / Case blocks for templates #5096

Closed
@mjadobson

Description

@mjadobson

I've had a couple times where I've missed a switch equivalent for logic in templates. I have been using long if-elseif chains, but this can get ugly. It's mostly useful for when you want to display different components based on an enum. Haven't seen any other issues about this, but switch statements are commonly used for control flow and I was a bit suprised they were absent in Svelte.

{#switch type}
    {:case 'loading'}
        <Loading />
    {:case 'success'}
        <Content />
    {:case 'timeout'}
        <Timeout />
    {:case 'error'}
        <ErrorMessage />
    {:default}
        <div>{status}</div>
{/switch}

<!-- or -->

{#case type}
    {:when '..'}
    {:else}
{/case}

as opposed to:

{#if type === 'loading'}
        <Loading />
    {:elseif type === 'success'}
        <Content />
    {:elseif type === 'timeout'}
        <Timeout />
    {:elseif type === 'error'}
        <ErrorMessage />
    {:else}
        <div>{status}</div>
{/switch}

<!-- or alternatively -->

<svelte:component this={(()=>{
    switch (type) {
        case 'loading':
            return Loading;
        case 'success':
            return Content;
        case 'timeout':
            return Timeout;
        case 'error':
           return ErrorMessage;
    }
})()}/>

EDIT: Just found this is a dupe: #530 - Feel free to close this and re-open the other issue.

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