Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Switch / Case blocks for templates #5096

Copy link
Copy link
Closed
@mjadobson

Description

@mjadobson
Issue body actions

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.

fdevoto, realfakenerd, derharry, jdgamble555, 1rens1 and 1 more

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

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.