SvelteKit gives us unique files for adding layouts. Using the +layout.svelte
file name, we can set layouts for all levels of routes. We can also set +error.svelte
in each route so that we can handle any errors for these routes.
We'll do that in this lesson by adding a <h1>Header</h1>
and <h4>Footer</h4>
that wraps a <slot />
to see it rendered on different pages. Notice that we will need to utilize <slot />
to render the routes content onto the page as well. This gives us finegrain control of where content goes in our layout.
Instructor: [0:00] building sites and applications, it's common to want to have layouts. For example, we want to have a header or footer but we don't want to have to include that on every page in our HTML. So we can build a layout that has the header and the footer in it and then that layout reps the rest of the pages.
[0:18] Here, in our Svelte app and go to routes and add a new file called pluslayout.svelte. Here, we can just add some simple styles and say, let's make this an H1 says, header, put a slot here. Then, let's make this an H4 that says footer.
[0:46] If we save that, we see we have our header here and our footer here. Now, if we go to the About page, we'll see the same thing. It's persistent across our routes. You can also do this with errors. If we come here to our routes and we add a new file of error.svelte, and let's just put, "You have an error," we know that it would be something like a status 404.
[1:18] If we save that, it's not going to show up yet. If we try to go to a route that doesn't exist...so let's try to go to Blog. Since we called it Post, what if we've forgotten, we call it Blog? We will hit "You have an error." We can see that this is pretty nice that we can give our site custom errors and layouts.
[1:39] You can also do this for each nested route. On the About page, we can add a layout here as well. Here, all we want to say is, let's put an H3, "You are on the About page." Now if we come back over and go to About, we see we also have "You are on the About page."
[2:01] Remember, we also have to include a slot on this page so that we have access to everything that comes below the Abouts directory. If we put slot, you'll see that we now have, if we go to the page.svelte, we see we're not getting this Hello from the About page, it's not over here. If we come back and we save that slot, you'll see that it shows up.
[2:22] In this lesson, we learned how to apply layouts to our application by adding the layout.svelte file here. This will apply layouts to our entire application. We also learned that we can apply layouts to our specific routes. This is what's called nested routing. We also learned that we can apply error messages or have error routes that catch any errors on our pages.