一个计算机技术爱好者与学习者

0%

好好学Hexo:Hexo Next主题显示文章更新时间

1. 问题

《Hexo更换主题为Next》一文中,关闭了文章的更新时间。因为next主题默认是使用markdown文件的修改时间作为更新时间,这个时间是不符合预期的。比如我换了电脑,clone下来markdown文件,写完后发布,那么所有文章的更新时间都会变成当前时间,这个就不符合预期,就不对。

但是,文章更新时间确实是有意义的,读者能够通过更新时间推断出一篇文章的有效性。比如很多工具和技术昨天可以用,文章写的没毛病,但是也许今天就不能用了。

本文就来研究一下,怎样让next主题显示符合预期的、准确的更新时间。

2. 思路

首先,我们知道next主题是支持显示更新时间的,只不过显示的更新时间不对。那么,能不能显示对的更新时间呢?看代码。

1、_config.yml,其中关于更新时间的部分:

1
2
3
4
5
6
7
8
# Post meta display settings
post_meta:
item_text: true
created_at: true
updated_at:
enable: true
another_day: true
categories: true

2、layout/_macro/post.swig,其中关于更新时间的部分:

1
2
3
4
5
6
7
8
9
10
11
12
13
{%- if theme.post_meta.updated_at.enable and datetime_diff %}
{%- set display_updated = not theme.post_meta.updated_at.another_day or theme.post_meta.updated_at.another_day and date_diff %}

{%- if display_updated or not theme.post_meta.created_at %}
<span class="post-meta-item">
<span class="post-meta-item-icon">
<i class="fa fa-calendar-check-o"></i>
</span>
<span class="post-meta-item-text">{{ __('post.edited') }}</span>
<time title="{{ __('post.modified') + __('symbol.colon') + full_date(post.updated) }}" itemprop="dateModified" datetime="{{ moment(post.updated).format() }}">{{ date(post.updated) }}</time>
</span>
{%- endif %}
{%- endif %}

由上面的代码我们可以得知:

  • 只要在文章头部yaml定义中添加 updated 字段,就可以显示我们自己定义的更新时间,而不是文件的修改时间。
  • 如果开启了 post_meta.updated_at.another_day ,当 date 和 updated 日期相同时,只会显示发布时间。

因此,我们现在有两个思路来实现next主题显示符合预期的更新时间。
思路一:开启 post_meta.updated_at.enable,然后给所有的md文件添加 updated 字段。
思路二:开启 post_meta.updated_at.enable,修改 post.swig ,令没有 updated 字段的md文件只显示发布时间,有 updated 字段的md文件显示发布时间和更新时间。

这里选择思路一,因为实现的逻辑最简单,而且郝同学的shell脚本用的还不错。

3. 实现

3.1. 开启更新时间显示

_config.yml,开启更新时间显示:

1
2
3
4
5
6
7
8
# Post meta display settings
post_meta:
item_text: true
created_at: true
updated_at:
enable: true
another_day: true
categories: true

3.2. 添加updated字段

1、准备脚本

1
2
3
4
5
6
7
8
9
#!/bin/bash

dir="_posts"
for file in `ls ${dir} | grep '.md'`;do
content=$(cat ${dir}/${file}| head -n 10 | grep 'date: ')
datestr=$(echo "$content" | awk '{print $2" "$3}')
newcontent="updated: "$datestr
sed -i "/$content/a\\$newcontent" ${dir}/${file}
done

2、执行脚本
把脚本放到 source 目录下,然后执行脚本 bash modify.sh
备注:需要linux环境,mac环境的sed命令和linux环境的sed命令有差异。