Svelte Each Blocks
Using Svelte Each Blocks to Iterate a List
Previously, we set up the LunchMenuAdmin
component to fetch data from our back end, but we didn't show the data to users in a friendly format. Since we are fetching an array (a list) of lunchWeek
objects, we can use a Svelte each
block to loop through the array and update the DOM with the results.
Take the example const myList = ['Apple', 'Orange', 'Kiwi']
. We can use a Svelte each
block to loop through the array and display the fruit:
<ul>
{#each myList as fruit}
<li>{fruit}</li>
{/each}
</ul>
This will translate to the following markup for the browser:
<ul>
<li>Apple</li>
<li>Orange</li>
<li>Kiwi</li>
</ul>
Let's apply this concept to our lunchWeekList
in LunchMenuAdmin.svelte
. Instead of using an unordered list, we'll use a table. The each
block will be wrapped around the table rows after the header:
<div>
<nav class="breadcrumb" aria-label="breadcrumbs">
<ul>
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/admin/manage-menus">Lunch Menu Administration</a>
</li>
<li class="is-active">
<a href="/#">{$user.schoolName}</a>
</li>
</ul>
</nav>
<table>
<thead>
<tr>
<th>Week Of</th>
<th>Published</th>
</tr>
</thead>
{#each lunchWeekList as lunchWeek}
<tr>
<td>{lunchWeek.weekOf}</td>
<td>{lunchWeek.isPublished}</td>
</tr>
{/each}
</table>
</div>

It's looking better, but we haven't applied our Bulma table class yet. Just add class="table"
to the table element:
<table class="table">
Even better, but it's not interactive yet. When an admin user views this data, they will need to be able to click on a given week and view or update lunch details for that week. We can add a click handler to each of the rows, and route the user to a new "Lunch Menu Admin Details" component.
Each lunchWeek
object has a lunchWeekId
property (1, 2, 3, etc). We can use this property to build a route convention that makes hierarchical sense, e.g.:
/admin/manage-menus
--> route to theLunchMenuAdmin.svelte
component/admin/manage-menus/week-details/1
--> route to a newLunchMenuAdminDetails.svelte
component were we can view/update the details for thelunchWeek
entity wherelunchWeekId = 1
.
Let's stub out a new LunchMenuAdminDetails.svelte
file:
This page is a preview of Fullstack Svelte