--- import BaseLayout from '../../layouts/BaseLayout.astro'; import { getCollection } from 'astro:content'; // 获取所有文章 const allPosts = await getCollection('blog', ({ data }) => { return !data.draft; }); // 构建分类树结构 interface CategoryNode { name: string; fullName: string; count: number; children: Map; posts: typeof allPosts; } function buildCategoryTree(posts: typeof allPosts): CategoryNode { const root: CategoryNode = { name: 'root', fullName: '', count: 0, children: new Map(), posts: [], }; posts.forEach((post) => { const category = post.data.category; if (!category) { root.posts.push(post); root.count++; return; } // 支持多级分类,用 / 分隔,如 "技术/前端/React" const parts = category.split('/').map((p) => p.trim()); let current = root; parts.forEach((part, index) => { const fullName = parts.slice(0, index + 1).join('/'); if (!current.children.has(part)) { current.children.set(part, { name: part, fullName: fullName, count: 0, children: new Map(), posts: [], }); } const node = current.children.get(part)!; node.count++; // 如果是最后一级,添加文章 if (index === parts.length - 1) { node.posts.push(post); } current = node; }); }); return root; } const categoryTree = buildCategoryTree(allPosts); // 统计总数 const totalCategories = (() => { let count = 0; function countNodes(node: CategoryNode) { count += node.children.size; node.children.forEach((child) => countNodes(child)); } countNodes(categoryTree); return count; })(); // 格式化日期 function formatDate(date: Date): string { return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'short', day: 'numeric', }); } // 递归渲染分类节点 function renderCategoryNode(node: CategoryNode, level: number): string { const sortedChildren = [...node.children.values()].sort((a, b) => a.name.localeCompare(b.name, 'zh-CN')); const hasChildren = sortedChildren.length > 0; const hasPosts = node.posts.length > 0; let html = ''; if (node.name !== 'root') { html += `
${hasChildren || hasPosts ? ` ` : '
'} ${node.name}
${node.count} 篇
`; } // 子内容 if (hasChildren || hasPosts) { const paddingClass = node.name === 'root' ? '' : 'category-content hidden'; html += `
`; // 文章列表 if (hasPosts) { html += `
`; node.posts.sort((a, b) => b.data.pubDate.valueOf() - a.data.pubDate.valueOf()).forEach((post) => { const slug = post.slug || post.id; html += ` ${post.data.title} ${formatDate(post.data.pubDate)} `; }); html += `
`; } // 子分类 sortedChildren.forEach((child) => { html += renderCategoryNode(child, level + 1); }); html += `
`; } if (node.name !== 'root') { html += `
`; } return html; } ---

文章分类

共 {totalCategories} 个分类,{allPosts.length} 篇文章

{categoryTree.children.size > 0 || categoryTree.posts.length > 0 ? (
{categoryTree.posts.length > 0 && (
未分类
{categoryTree.posts.length} 篇
)}
) : (

暂无分类

)}