In this tutorial you will learn how to create a blog with SvelteKit content and layouts.
A blog in SvelteKit consists of a page that lists all the blog posts, and a series of content pages with a date for the posts. That’s all there is to it.
We’re going to use mdsvex to render our Markdown posts. It’s a Markdown preprocessor for Svelte which allows you to use Svelte templating and components amongst your Markdown.
Let’s start by installing mdsvex.
Now we need to configure SvelteKit to use mdsvex for
.svx files in our
The one curious line in the above config is where we set the layout. Any
.svx will use this layout by default. It doesn’t exist yet so let’s create it. Create a directory called
blog inside the routes folder and inside create
_post.svelte with the following:
We’re setting props for
date which will be set through front matter in our post (we’ll get to this soon). The rest of this is similar to our first layout, we’re setting a
<title>, some elements on the page, then calling
<slot /> for our content.
SvelteKit nests layouts by default, so it will work up the directory tree applying any
__layout.svelte that it finds. So SvelteKit will render our post pages using the following resources:
Each post is a Markdown file and lives in the
/src/routes/blog/ directory we created before. Now let’s create three blog posts:
You might be wondering what the triple dashed lines are. They indicate front matter, which is a way to set metadata for the page. We’ve already set up props in the post layout for this metadata so they’ll automatically be initialized.
Finally we need to create a page which lists all the blog posts. Create
/src/routes/blog/index.svelte with the following:
There’s a lot going on here so let’s break it down.
First, we collect all the post modules in the current directory:
Then we create an array of promises that extracts the metadata from each blog post. The path has the file extension of the post whereas the end URL will not, so we remove it:
SvelteKit components can define a load function which runs before the component is loaded. We’re using this function to execute all the promises and save the results to the page props:
And finally, we iterate over the posts prop to output a list of posts:
There’s one last step before we take a look at the blog in the browser, add the blog to the navigation. Open up your
Nav component and add a link to the blog:
That’s all there is to it! Open the site up in the browser and take a browse through your blog.
In our final lesson, we’ll use a generated JSON file to populate a map with the top dog parks.