Slim template: conditional logic

Learn how to use templates in Svelte, especially how to use conditional sentences

Any good template language on the web provides at least two things: conditional structure and loops.

Svelte is no exception. In this article, I will study conditional structures.

You want to be able to view a value/expression, if the value/value points to a true value, perform certain operations, and if the value/value points to a false value, perform other operations.

Svelte provides us with a very powerful set of control structures.

first of allin case:

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

Has an opening{#if}And ending{/if}. The beginning tag checks whether the value or statement is true. under these circumstancesisRedCan be a boolean with boolean valuetruevalue:

<script>
let isRed = true
</script>

An empty string is false, but a string containing some content is false.

0 is false, but a number> 0 is true.

Boolean valuetrueOf course it is true, andfalseIs false.

If the open flag is not met (a false value is provided), nothing will happen.

If you are not satisfied, you can do other things, we use the appropriateelsestatement:

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

The first block will be rendered in the template, or the second block will be rendered in the template. There is no other choice.

You can use any JavaScript expression in itifBlocking conditions, so you can use!operator:

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

now atelseYou may need to check other conditions. That is{:else if somethingElse}Here comes the syntax:

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

You can have many such blocks, not just one, and you can nest them. This is 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}

Download mine for freeSlim Handbook


More subtle tutorials: