Skip to content

{#switch .... } block #7536

Closed
Closed
@p-lau

Description

@p-lau

Describe the problem

I'm always frustrated when...

I use the {#if expression}...{:else if expression}...{:else}...{/if} over a string or integer value.

The example given in the docs is nice, but when I need to extend it, I would see:

{#if status === '404'}
	<p>Can't find it!</p>
{:else status === '200'}
	<p>Just right!</p>
{:else if status === '500'}
	<p>Server gone wrong.</p>
<!-- add in however many  {:else if status === ... } statements. -->
{:else}
	<p>Something is wrong!</p>
{/if}

Describe the proposed solution

I would like to see...

a {#switch ....} block.

My proposed idea would mimic the switch statement in JS.

{#switch status}
{:case '404'}
	<p>Something is not right!</p>
{:case '200'}
	<p>Just right!</p>
{:case '500'}
	<p>Server gone wrong.</p>
<!-- insert however many {:case ...} statements -->
{:default}
	<p>Something is wrong!</p>
{/switch}

In case we want to have fall-through:

{#switch type}
{:case 'cat'}
{:case 'dog'}
{:case 'parrot'}
{:case 'fish'}
{:case 'hamster'}
	<p>They would make a nice pet!</p>
{:case 'alligator'}
{:case 'tiger'}
	<p>They belong in a sanctuary!</p>
{:default}
	<p>I don't know these...</p>
{/switch}

or maybe...

{#switch type}
{:case 'cat', 'dog', 'parrot', 'fish', 'hamster'}
	<p>They would make a nice pet!</p>
{:case 'alligator', 'tiger'}
	<p>They belong in a sanctuary!</p>
{:case 'ufo'}
{:default}
	<p>I don't know where these would belong...</p>
{/switch}

NOTE: As for using breaks, I imagine it would be automatically used if following {:case} is a Svelte component or HTML tag. If after {:case ....} is empty or another {:case}, there would be fall-through, like the two fall-through examples above.

Alternatives considered

I'm still using the {#if else} block, and while even the Javascript switch function isn't used often, I think this would just be a nice-to-have.

Importance

nice to have

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