ข้ามไปยังเนื้อหา

Rendering Markdown

ใน Next.js พร้อม contentlayer คุณ import MDX component โดยตรง ใน Astro คุณเรียก render(entry) (Astro 5+) หรือ await entry.render() เพื่อรับ Content component แล้วใช้ <Content /> ใน template

ต้องใช้โปรเจกต์ Astro เต็มรูปแบบ ใช้ npm create astro@latest เพื่อสร้างโปรเจกต์

React
// app/blog/[slug]/page.tsx (Next.js App Router + contentlayer)
import { allPosts, Post } from 'contentlayer/generated';
import { useMDXComponent } from 'next-contentlayer/hooks';
export default function PostPage({ params }: { params: { slug: string } }) {
const post = allPosts.find((p) => p.slugAsParams === params.slug)!;
const MDXContent = useMDXComponent(post.body.code);
return (
<article>
<h1>{post.title}</h1>
<MDXContent />
</article>
);
}
Astro
---
// src/pages/blog/[slug].astro (Astro 5+)
import { getCollection, render } from 'astro:content';
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 render(entry);
---
<article>
<h1>{entry.data.title}</h1>
<Content />
</article>

render(entry) คืนค่า object { Content, headings, remarkPluginFrontmatter } ใช้ <Content /> เพื่อ render Markdown/MDX ที่ compile แล้วใน template

React
// app/blog/page.tsx (Next.js App Router + contentlayer)
import { allPosts } from 'contentlayer/generated';
import Link from 'next/link';
export default function BlogIndex() {
const posts = allPosts.sort(
(a, b) => new Date(b.date).getTime() - new Date(a.date).getTime()
);
return (
<ul>
{posts.map((post) => (
<li key={post._id}>
<Link href={post.url}>{post.title}</Link>
</li>
))}
</ul>
);
}
Astro
---
// src/pages/blog/index.astro (Astro)
import { getCollection } from 'astro:content';
const posts = await getCollection('blog', ({ data }) => !data.draft);
const sorted = posts.sort(
(a, b) => b.data.date.valueOf() - a.data.date.valueOf()
);
---
<ul>
{sorted.map((post) => (
<li>
<a href={`/blog/${post.slug}/`}>{post.data.title}</a>
</li>
))}
</ul>

getCollection รองรับ optional filter function ที่ argument ที่สอง — ที่นี่ใช้กรอง draft posts ออก

ฟังก์ชันใดที่เรียกเพื่อรับ renderable component จาก collection entry?
แสดงเนื้อหาที่ render แล้วใน Astro template อย่างไร?
`getStaticPaths()` คืนค่าอะไรสำหรับ dynamic collection route?