Jamstack Explorers

Building with SvelteKit and GraphCMS with Scott Spence

Svelte each directive

Okey dokey, in this mission, we're going to be adding some markup to our project index page. In the previous mission, we used the GraphQL client to fetch the launches data from our GraphCMS endpoint and display it on the home page here. Now, we're going to loop through this data and create an unordered list for it. So for each of these objects, here, I'm going to create a list item inside an unordered list. If I hop on over to my text editor VS code and move this over to the side, don't need that pre tag anymore. I'm gonna want an unordered list with a list item, for each mission we have in the list here.

And we're gonna have an a tag here, which has got a link to the mission page. We'll come on to the page later. And in here, we're going to have a h2 with the mission name, and using the time HTML tag, gonna have the date. So to loop through this, we're using the Svelte each directive, which looks like this hash tag each, and then the array we're looping through, which is launches. And then the variable for each iteration of the loop, we're going to need to close the each loop down here, which is curly braces, forward slash each now can start populating the data for the list items. So the link for this will be launch slug and we have launch name and launch date. Now if I hit save, We have an unordered list here.

Cool. So one last thing we could do with the each directive here is rather than use a variable, we can actually pulled out the properties of the array. So it could bring out a slug. name and date. And then replace remove each one of these here. Hit save again. Brilliant! Okay, so that's it for the each directive. If you want to get a bit more information on templating with Svelte and SvelteKit you can go over to the Svelte dot dev docs, and check out the template syntax.

There's many more directives to use we'll be using the if in a later mission. But for now, that's it. In the next one, we'll be taking a look at routing in SvelteKit. So in the next one, bye


your progress