--- title: Logic blocks --- ## {#if ...} ```svelte {#if expression}...{/if} ``` ```svelte {#if expression}...{:else if expression}...{/if} ``` ```svelte {#if expression}...{:else}...{/if} ``` Content that is conditionally rendered can be wrapped in an if block. ```svelte {#if answer === 42}
what was the question?
{/if} ``` Additional conditions can be added with `{:else if expression}`, optionally ending in an `{:else}` clause. ```svelte {#if porridge.temperature > 100}too hot!
{:else if 80 > porridge.temperature}too cold!
{:else}just right!
{/if} ``` (Blocks don't have to wrap elements, they can also wrap text within elements!) ## {#each ...} ```svelte {#each expression as name}...{/each} ``` ```svelte {#each expression as name, index}...{/each} ``` ```svelte {#each expression as name (key)}...{/each} ``` ```svelte {#each expression as name, index (key)}...{/each} ``` ```svelte {#each expression as name}...{:else}...{/each} ``` Iterating over lists of values can be done with an each block. ```svelte{todo.text}
{:else}No tasks today!
{/each} ``` Since Svelte 4 it is possible to iterate over iterables like `Map` or `Set`. Iterables need to be finite and static (they shouldn't change while being iterated over). Under the hood, they are transformed to an array using `Array.from` before being passed off to rendering. If you're writing performance-sensitive code, try to avoid iterables and use regular arrays as they are more performant. ## {#await ...} ```svelte {#await expression}...{:then name}...{:catch name}...{/await} ``` ```svelte {#await expression}...{:then name}...{/await} ``` ```svelte {#await expression then name}...{/await} ``` ```svelte {#await expression catch name}...{/await} ``` Await blocks allow you to branch on the three possible states of a Promise — pending, fulfilled or rejected. In SSR mode, only the pending state will be rendered on the server. ```svelte {#await promise}waiting for the promise to resolve...
{:then value}The value is {value}
{:catch error}Something went wrong: {error.message}
{/await} ``` The `catch` block can be omitted if you don't need to render anything when the promise rejects (or no error is possible). ```svelte {#await promise}waiting for the promise to resolve...
{:then value}The value is {value}
{/await} ``` If you don't care about the pending state, you can also omit the initial block. ```svelte {#await promise then value}The value is {value}
{/await} ``` Similarly, if you only want to show the error state, you can omit the `then` block. ```svelte {#await promise catch error}The error is {error}
{/await} ``` ## {#key ...} ```svelte {#key expression}...{/key} ``` Key blocks destroy and recreate their contents when the value of an expression changes. This is useful if you want an element to play its transition whenever a value changes. ```svelte {#key value}