写着写着发现 Posts 页面东西太多了。
习惯性的把工作记录也存档了,但是混在post里看起来有点乱。
毕竟日常post和工作区别比较大,还是分成两个页面吧。
目标
由于 Category 设置的比较多,选择通过 tag 分离,标记有工作记录的tag独立显示在 Works 这个栏目里,其他的显示在 Posts 里。
第一次
第一次直接改了 layout/_page/archive.ejs 文件,修改原archive显示逻辑,并且新添加一个works.ejs显示新页面。
结果越改bug越多,主要是和 hexo 的 per_page 冲突了,而且 tag 功能中,点击tag会跳转到所有包含此tag的archive页面,但如果在archive限制了不显示工作记录,则tag中点击工作记录则会显示空白。
修改步骤
步骤 1:创建 works 页面模板
在 themes/Chic/layout/_page/ 目录下创建新文件 works-archive.ejs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <div class="post-wrap archive"> <% var last_year = ''; %> <% page.posts.each(function (post) { %> <% var cur_year = post.date.year(); %>
<% if(last_year !== cur_year){ %> <h3><%- cur_year %></h3> <% last_year = cur_year; } %>
<article class="archive-item"> <a class="archive-item-link" href="<%- url_for(post.path) %>"><%= post.title %></a> <span class="archive-item-date"><%- date(post.date, theme.date_format) %></span> </article> <% }) %> <%- partial('_partial/paginator') %> </div>
|
步骤 2:修改 archive.ejs 模板
在 themes/Chic/layout/_page/archive.ejs 中,确保默认显示非工作记录的文章。如果使用自定义生成器(见步骤 3),该文件可保持不变。
步骤 3:添加自定义生成器脚本
在博客根目录的 scripts/ 文件夹下创建 custom-archive.js 文件:
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
| const pagination = require('hexo-pagination');
hexo.extend.generator.register('custom_archive', function(locals) { const filteredPosts = locals.posts.filter(post => { if (!post.tags || post.tags.length === 0) return true; return !post.tags.some(tag => tag.name === '工作记录'); }).sort('-date');
const config = this.config; const perPage = config.per_page || 10;
return pagination('archives', filteredPosts, { perPage: perPage, layout: ['archive', 'index'], format: 'page/%d/', data: {} }); });
hexo.extend.generator.register('works_archive', function(locals) { const worksPosts = locals.posts.filter(post => { if (!post.tags || post.tags.length === 0) return false; return post.tags.some(tag => tag.name === '工作记录'); }).sort('-date');
const config = this.config; const perPage = config.per_page || 10;
return pagination('works', worksPosts, { perPage: perPage, layout: ['works-archive', 'archive'], format: 'page/%d/', data: {} }); });
|
步骤 4:配置导航菜单(可选)
在 themes/Chic/_config.yml 中添加 Works 导航链接:
1 2 3 4 5
| nav: Home: / Archives: /archives Works: /works About: /about
|
原理说明
custom_archive 生成器创建 /archives 页面,排除所有包含”工作记录”标签的文章
works_archive 生成器创建 /works 页面,仅显示包含”工作记录”标签的文章
- 通过 Hexo 的
hexo-pagination 模块实现分页功能
filter() 方法根据标签名称进行筛选,确保两个页面互不重复