前言 Hexo Butterfly 主题自带了 series 标签插件,但需要在每篇文章中手动插入 {% series %} 标签。为了更优雅地展示系列文章,我们可以通过修改主题源码,实现在文章侧边栏自动判断并显示系列文章导航目录。
实现效果 当文章的 Front-matter 中包含 series: 系列名称 时,文章页面的侧边栏(公告栏下方、目录栏上方)会自动显示一个精美的导航卡片,列出该系列下的所有文章,并高亮当前阅读的文章。
修改步骤 1. 新建侧边栏挂件模板 在 themes/butterfly/layout/includes/widget/ 目录下新建文件 card_series_nav.pug,内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 - var series = page.series if series - var series_posts = groupPosts()[series] if series_posts && series_posts.length > 0 .card-widget.card-series-nav .item-headline i.fas.fa-layer-group span= '系列文章 - ' + series .card-content .series-nav-list each item, index in series_posts - var active = item.path === page.path ? 'active' : '' a.series-nav-item(href=url_for(item.path) class=active title=item.title) span.series-nav-item-index= (index + 1) + '.' span.series-nav-item-title= item.title
2. 注册挂件到侧边栏布局 修改 themes/butterfly/layout/includes/widget/index.pug 文件,将挂件引入到合适的位置(例如公告栏和目录之间)。
找到 !=partial('includes/widget/card_announcement', {}, {cache: true}) 这一行,在它下面添加 include ./card_series_nav.pug。
修改后的代码片段如下:
1 2 3 4 5 6 7 8 //- ... !=partial('includes/widget/card_announcement', {}, {cache: true}) //- 插入系列文章导航挂件 include ./card_series_nav.pug !=partial('includes/widget/card_top_self', {}, {cache: true}) //- ...
3. 添加 CSS 样式 在 source/css/custom.css 中添加以下样式,适配侧边栏的尺寸和风格:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 .card-series-nav .series-nav-list { display : flex; flex-direction : column; gap : 4px ; padding : 0 10px 10px 10px ; } .series-nav-item { display : flex; align-items : center; padding : 6px 10px ; border-radius : 6px ; text-decoration : none !important ; color : var (--font-color) !important ; transition : all 0.3s ; font-size : 14px ; line-height : 1.4 ; } .series-nav-item :hover { background : var (--text-bg-hover); color : var (--white) !important ; transform : translateX (4px ); } .series-nav-item .active { background : var (--btn-bg); color : var (--btn-color) !important ; font-weight : bold; box-shadow : 0 2px 6px rgba (0 ,0 ,0 ,0.1 ); } .series-nav-item .active :hover { background : var (--btn-hover-color); } .series-nav-item-index { margin-right : 6px ; opacity : 0.8 ; font-family : Consolas, monospace; min-width : 20px ; }
使用方法 只需在文章的 Front-matter 中设置 series 属性即可:
1 2 3 4 --- title: 我的文章标题 series: Hexo教程 ---
主题会自动识别并生成该系列的侧边栏导航目录。