让hexo的分类列表支持子分类导航(优化版)
如果您发现本文排版有问题,可以先点击下面的链接切换至老版进行查看!!!
让hexo的分类列表支持子分类导航(优化版)
之前写过hexo的分类列表支持子分类导航,简单回顾下需求,就是想让列表页能够根据不同的年份来切换,效果如下:

review
当时采用的临时方案,虽然效果是达到了,但是具体实现不够优雅,里面还有hardcode,代码如下
let categoryParent='';
page.posts.sort('date', -1).each(function(post){
if(post._categoryParent) {
categoryParent = post._categoryParent;
}
})
let yearList=['2021', '2020', '2019'];
- 每篇文章还需要配置_categoryParent,就是为了在category.ejs里面读取,其实url上面就有这部分信息
- yearList是直接在编码中写死的,这个才是需要配置的
refactor
-
在尝试从location获取_categoryParent时报错了,提示location未定义,在hexo官网看文档发现可以在page.path或者全局变量url里面获取。
let pathList = page.path.split('/'); let categoryIndex = pathList.indexOf(page.category) let categoryParent = pathList[categoryIndex - 1];根据/分割,在年份信息前面那个就是categoryParent信息啦。
-
在配置表里面配置年份信息 比如这样配置 用形如_xxYearList的配置项。
# training展示年份列表 _trainingYearList: 2021,2020,2019我们可以这样读取
let conf = theme['_' + categoryParent + 'YearList']; if (conf) { let yearList = conf.split(','); ... }
完整代码
let pathList = page.path.split('/');
let categoryIndex = pathList.indexOf(page.category)
let categoryParent = pathList[categoryIndex - 1];
let conf = theme['_' + categoryParent + 'YearList'];
if (conf) {
let yearList = conf.split(',');
if (yearList) {
yearList.forEach(function (year) {%>
<a href="<%- url_for('/' + config.category_dir + '/' + categoryParent + '/' + year + '/')%>" class="category_year-a <%- year === page.category ? 'active' : ''%>"><%- year%></a>
<%})
}
}
后面其他需要使用按年份细分的列表,我们直接这样配置就好了
# events展示年份列表
_eventsYearList: 2022,2020,2019,2017- 分类:
- Web前端
更新时间:
上一篇:下一篇:
