In this blog post, we’ll explore how to work with templates in Svelte, focusing specifically on the use of conditionals.

A good templating language for the web typically provides two essential features: a conditional structure and a loop. Svelte is no exception, and in this post, we’ll dive into the conditional structures available in Svelte.

One of the control structures provided by Svelte is the if statement:

{#if isRed}
   <p>Red</p>
{/if}

In the above code snippet, the opening {#if} statement checks if the value or expression isRed is truthy. For example, isRed can be a boolean with a value of true:

<script>
   let isRed = true;
</script>

In Svelte, an empty string is considered falsy, while a string with content is considered truthy. Similarly, 0 is considered falsy, but any number greater than 0 is considered truthy. Booleans follow their expected truthy-falsy rules.

If the condition specified in the {#if} statement is not satisfied (i.e., a falsy value is provided), then nothing happens. To handle the case where the condition is not satisfied, we can use the {:else} statement:

{#if isRed}
   <p>Red</p>
{:else}
   <p>Not red</p>
{/if}

In the above code snippet, either the first block or the second block will be rendered in the template. There’s no other option.

You can use any JavaScript expression in the condition of the if block. For example, you can negate a condition using the ! operator:

{#if !isRed}
   <p>Not red</p>
{:else}
   <p>Red</p>
{/if}

Additionally, inside the else block, you can check for another condition using the {:else if somethingElse} syntax:

{#if isRed}
   <p>Red</p>
{:else if isGreen}
   <p>Green</p>
{:else}
   <p>Not red nor green</p>
{/if}

You can have multiple of these conditional blocks, and they can be nested as well. Here’s a more complex example:

{#if isRed}
   <p>Red</p>
{:else if isGreen}
   <p>Green</p>
{:else if isBlue}
   <p>It is blue</p>
{:else}
   {#if isDog}
      <p>It is a dog</p>
   {/if}
{/if}

Tags: Svelte, templates, conditional logic