--- import { getCollection, render } from 'astro:content'; import { contentStructure, getRelativePath, getBasename, getDirPath } from '../../content.config'; import type { SectionStructure } from '../../content.config'; import Layout from '../../components/Layout.astro'; import Breadcrumb from '../../components/Breadcrumb.astro'; // 添加这一行,告诉Astro预渲染这个页面 export const prerender = true; export async function getStaticPaths() { const articles = await getCollection('articles'); // 为每篇文章添加section信息 const articlesWithSections = articles.map(article => { // 查找文章所属的目录 let section = ''; const findSection = (sections: SectionStructure[], articleId: string, parentPath = ''): string | null => { for (const sec of sections) { const sectionPath = parentPath ? `${parentPath}/${sec.name}` : sec.name; // 检查文章是否在当前目录中 for (const artPath of sec.articles) { const artId = getRelativePath(artPath); const basename = getBasename(artPath); const dirPath = getDirPath(artPath); // 尝试多种可能的ID格式 const possibleIds = [ artId, // 完整相对路径 `${sectionPath}/${basename}`, // 目录路径/文件名 basename, // 仅文件名 dirPath ? `${dirPath}/${basename}` : basename, // 目录路径/文件名 `articles/${artId}`, // 添加集合名称前缀 `articles/${sectionPath}/${basename}` // 添加集合名称前缀和目录路径 ]; // 精确匹配 if (possibleIds.includes(articleId)) { return sectionPath; } // 检查文章ID是否以某个可能的ID结尾 for (const possibleId of possibleIds) { if (articleId.endsWith(possibleId)) { return sectionPath; } } } // 递归检查子目录 const foundInSubsection = findSection(sec.sections, articleId, sectionPath); if (foundInSubsection) { return foundInSubsection; } } return null; }; section = findSection(contentStructure.sections, article.id) || ''; return { ...article, section }; }); return articlesWithSections.map(article => { return { params: { id: article.id }, props: { article, section: article.section } }; }); } // 获取文章内容 const { article, section } = Astro.props; // 渲染文章内容 const { Content } = await render(article); // 获取面包屑导航 const breadcrumbs = section ? section.split('/') : []; // 获取相关文章 const allArticles = await getCollection('articles'); const relatedArticles = allArticles .filter(a => a.id !== article.id && ( (a.data.tags && article.data.tags && a.data.tags.some(tag => article.data.tags?.includes(tag))) )) .sort((a, b) => b.data.date.getTime() - a.data.date.getTime()) .slice(0, 3); ---
{/* 返回按钮 */} 返回文章列表

{article.data.title}

{/* 显示文章所在目录 */} {section && ( {section} )}
{article.data.tags && article.data.tags.length > 0 && (
{article.data.tags.map(tag => ( #{tag} ))}
)} {article.data.summary && (
{article.data.summary}
)}
{relatedArticles.length > 0 && ( )}