第3节:Hexo frontmatter 日期管理

背景

博客文章多了之后,发现 front matter 中的 date 字段存在一些问题:

  1. 部分文章的 date 不准,有的是手动填的随意日期
  2. 缺少 updated 字段,无法知道文章最后更新时间
  3. 文章排序(按时间)不够准确

方案

利用 Git 历史统一校正所有文章的日期:

字段 来源 含义
date Git 首提交时间 文件进入版本库的创建时间
updated Git 末提交时间 文件最后修改的提交时间

规则:

  • updated 仅在末提交时间 > 首提交时间时才写入,从未修改过的文章不写
  • 未来新文章只写 date,不写 updated(等以后修改了再补)

主题改造

在 landscape 主题的 date.ejs 中添加判断:如果文章有 updated 字段,则显示「发表于 X · 更新于 Y」;否则保持原样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<% if (post.updated){ %>
<span class="<%= class_name %>">
<a href="<%- url_for(post.path) %>">
<time datetime="<%= date_xml(post.date) %>" itemprop="datePublished">
发表于 <%= date(post.date, date_format) %>
</time>
</a>
<span class="article-updated">
· 更新于 <%= date(post.updated, date_format) %>
</span>
</span>
<% } else { %>
<a href="<%- url_for(post.path) %>" class="<%= class_name %>">
<time datetime="<%= date_xml(post.date) %>" itemprop="datePublished">
<%= date(post.date, date_format) %>
</time>
</a>
<% } %>

批量更新脚本

用 Node.js 脚本遍历所有 477 个文件,通过 git log --follow --format="%ai" 获取每篇文章的首末提交时间,批量写入 front matter。