ブログ構築
コンテンツコレクションを設定する
コンテンツコレクションとは要するにデータ置き場。/src/content/ 直下のフォルダを親として、配下のファイルやフォルダをコンテンツとしてグループ化するような感じ。
/src/content/blogを作成してその中にpost-1.mdを作成
/src/content/blog/post-1.md
---
title: ブログ記事1
---
## 最初のブログ記事です
あいうえお
/tsconfig.jsonに追記 → TypeScript のセットアップ
これをやらないと VSCode に怒られる。やっても怒られることがあるが、再起動すれば機嫌を直してくれる(かもしれない)。
/tsconfig.json
{
"extends": "astro/tsconfigs/base",
"compilerOptions": {
"strictNullChecks": true,
"allowJs": true
}
}
/src/content/config.tsを作成して追記
/src/content/config.ts
import { z, defineCollection } from 'astro:content';
const blogCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
}),
});
export const collections = {
blog: blogCollection,
};
記事の目次を作る → コレクションのクエリ
/src/pages/blog.astro を作成して追記する。
/src/pages/blog.astro
---
import { getCollection } from 'astro:content';
import BlogLayout from '../layouts/BlogLayout.astro';
const posts = await getCollection('blog');
---
<BlogLayout title="Blog">
<h2>記事一覧</h2>
<ul>
{
posts.map((post) => (
<li>
<a href={`/posts/${post.slug}/`}>{post.data.title}</a>
</li>
))
}
</ul>
</BlogLayout>
記事のテンプレートを作る → コンテンツからルーティングを生成
/src/posts/[slug].astro を作成して追記する。
このファイルによって /posts/post-1/ のような記事が作られる。
/src/posts/[slug].astro
---
import { getCollection } from 'astro:content';
import BlogLayout from '../../layouts/BlogLayout.astro';
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((entry) => ({
params: { slug: entry.slug },
props: { entry },
}));
}
const { entry } = Astro.props;
const { Content } = await entry.render();
---
<BlogLayout frontmatter={entry.data}>
<Content />
</BlogLayout>
リンク(重要)
/src/layouts/Nav.astro
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/page-test/">ページテスト</a></li>
<li><a href="/blog/">Blog</a></li>
</ul>
</nav>