Svelte - Logic



Logic is the key capability of the svelte that enables conditional rendering, data manipulation, and event handling. Svelte, a frontend framework, allows you to use JavaScript logic directly in your HTML templates.

What is Logic in Svelte?

Logic is a capability of the Svelte that allows it to use conditional statements and loops. HTML is not capable of handling logic such as loops or if/else statements, but Svelte is capable of it. Svelte has different kinds of logic, such as:

If Blocks

Svelte's if blocks allow you to conditionally display or hide parts of your template based on specific conditions. If the condition of the if statements is true, the template code inside the if block will be executed.

Syntax

{#if condition}
<!-- Content to render if condition is true -->
{/if}

Else Blocks

In Svelte, if the condition of the if block becomes false, the template code within the else block will be executed. Else blocks are used to show different content when the if condition is false.

Syntax

{#if condition}
{:else}
    <!-- Content to render if none of the above conditions 
    are true -->
{/if}

Else-if Blocks

If the if condition is false, Svelte then checks the condition in the else if block. If this condition is true, the code inside the else if block runs.

Syntax

{#if condition1}
{:else if condition2}
    <!-- Content to render if anotherCondition is true -->
{:else}
{/if}

Each Blocks

In Svelte, each block allows you to iterate over a list of items and create a piece of HTML for each item. Each Block makes it easy to work with arrays of data in your applications.

Syntax

{#each items as item}
   <li>{item.name}</li>
{/each}

Keyed Each Block

In Svelte, a keyed each keyed each block is a special kind of each block that allows you give each item in a list a unique key. This key helps Svelte quickly update the list by knowing which items have changed, been added, or removed.

Syntax

{#each items as item, key}
   <li key={key}>{item}</li>
{/each}

Await Blocks

The await block makes it easier to work with tasks that take time, like getting data from APIs. It lets you choose what to display while waiting for the task to finish.

Syntax

{#await promise}
  <!-- Content to display while the promise is pending -->
{:then value}
  <!-- Content to display when the promise resolves successfully -->
{:catch error}
  <!-- Content to display if the promise is rejected -->
{/await}

Example

The following example is illustrating the use of Each Block logic while displaying the list of fruits.

<!--App.svelte-->
<script>
    let fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
</script>

<h1>Fruit List</h1>

<ul>
    {#each fruits as fruit}
    <li>{fruit}</li>
    {/each}
</ul>

Output

Each-block-example
Advertisements