如何获取Docusaurus自动生成侧边栏分类的项目数量?
获取Docusaurus侧边栏分类的项目数量
Docusaurus默认没有提供直接获取侧边栏分类项目数量的内置功能,但可以通过主题API自定义实现自动计数的需求,新增文件时计数会自动同步更新,具体方法如下:
方法1:侧边栏分类标题旁显示计数
如果需要在侧边栏的分类标题旁标注项目数量,可以结合useSidebar钩子自定义组件实现:
- 创建自定义组件,读取侧边栏结构并统计目标分类的子项数量:
import { useSidebar } from '@docusaurus/theme-common'; export default function SidebarCategoryCount({ categoryLabel }) { const sidebar = useSidebar(); const targetCategory = sidebar?.items.find( item => item.type === 'category' && item.label === categoryLabel ); const count = targetCategory?.items.length || 0; return <span style={{ marginLeft: '8px', opacity: 0.7 }}>({count})</span>; }
- 通过主题配置替换默认的侧边栏分类组件,将计数组件嵌入分类标题中;或者在自定义侧边栏布局中直接调用该组件,传入目标分类的标签(比如
Foo)即可。
方法2:页面内显示当前分类计数
如果需要在分类下的页面中展示该分类的项目总数,可使用useCurrentSidebarCategory钩子:
import { useCurrentSidebarCategory } from '@docusaurus/theme-common'; export default function PageCategoryCount() { const currentCategory = useCurrentSidebarCategory(); return <div className="category-count-badge">本分类共 {currentCategory.items.length} 篇内容</div>; }
将该组件添加到页面的合适位置(如页头、侧边栏顶部),就能自动显示当前分类的项目数量,新增文件后计数会自动递增,无需手动修改。
无论你是手动配置侧边栏,还是使用autogenerated自动生成侧边栏,以上方法均能生效——因为钩子获取的是Docusaurus最终构建完成的侧边栏结构数据。
内容的提问来源于stack exchange,提问作者Pawan
相关产品推荐
相关产品推荐

