4 Block structures

 

This chapter covers

  • Conditional logic in HTML with #if
  • Iteration in HTML with #each
  • Waiting on promises in HTML with #await

There are three common approaches to adding conditional and iteration logic in the markup of various web frameworks. React uses JSX ( JavaScript XML) where logic is implemented by JavaScript code in curly braces (https://reactjs.org/docs/ introducing-jsx.html). Angular and Vue support framework-specific attributes for logic. For example, Angular supports ngIf and ngFor, while Vue supports v-if and v-for. Svelte supports a Mustache-like (https://mustache.github.io/) custom syntax that wraps HTML and the components to render.

There are only three kinds of block structures in Svelte:

  • if is used to specify conditional logic that determines whether something should be rendered.
  • each is used to iterate over a collection of data, rendering something for each piece of data.
  • await waits for a promise to resolve and renders something using that data.

Each of these defines blocks of HTML to render. They begin with {#name}, end with {/name}, and can contain {:name} intermediate markers. The # character indicates a block opening tag. The / character indicates a block ending tag. The : character indicates a block continuation tag. Read on to learn how to use these block structures.

4.1 Conditional logic with {#if}

4.2 Iteration with {#each}

4.3 Promises with {#await}

4.4 Building the Travel Packing app

4.4.1 Item component

4.4.2 Utility functions

4.4.3 Category component

4.4.4 Checklist component

4.4.5 App component

4.4.6 Try it

Summary