--- title: Control flow --- - if - each - await (or move that into some kind of data loading section?) - NOT: key (move into transition section, because that's the common use case) Svelte augments HTML with control flow blocks to be able to express conditionally rendered content or lists. The syntax between these blocks is the same: - `{#` denotes the start of a block - `{:` denotes a different branch part of the block. Depending on the block, there can be multiple of these - `{/` denotes the end of a block ## {#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} ``` 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. ## Other block types Svelte also provides [`#snippet`](snippets), [`#key`](transitions-and-animations) and [`#await`](data-fetching) blocks. You can find out more about them in their respective sections.