最近发现一直有流量会访问到我很早之前写的文章,但随着时间的变化,文章的内容可能已经不适用于现在了。比较喜欢 v2ex 的风格,对很久以前的文章增加一个 tip,告诉读者要注意文章的时效性。

https://www.v2ex.com/t/53623

本着一个对读者负责任的态度,希望读者可以注意到文章时效性的问题,能对文章有一个主观的判断,避免因为时效性问题而走弯路,所以我决定给 Hexo 时间久远文章加上一个友好的提示,因为我本人的博客是 Butterfly 的主题,所以只适配了 Butterfly,也许也适用于使用 Pug 渲染器的主题,大家可以随意取用。
使用 JavaScript 实现,只需修改 Butterfly 主题的两个文件。
在 themes/Butterfly/layout/includes/post 目录下新增一个 timecount.pug 文件,内容如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
script.
var now = new Date()
now = now.getTime() // 当前时间戳

var postinfo = document.getElementsByClassName("post-meta__date-created")[0]
var postinfo__date_created = new Date(postinfo.title.split(" ")[1].replace(/-/,"/"))
postinfo__date_created = postinfo__date_created.getTime() // 文章发布时间戳
//console.log("文章创建时间",postinfo__date_created)

var datepassing = parseInt(now - postinfo__date_created)
//console.log("过期时间",datepassing)
// 超过31天提示:3600*24*31*1000
if(datepassing > 2678400000){
var timecount = document.getElementsByClassName("post-timecount")[0]
var out = parseInt(datepassing / 86400000)
timecount.innerHTML = "<div class=\"note info\"><p><strong>文章有效性提示 Article Validity Tips</strong><br>这是一篇创建于 " + out + " 天前的文章,其中的信息可能已经有所发展或是发生改变。<br>This is an article that was created " + out + " days ago, and the information may have evolved or changed.</p></div>"
}

更新
2020 年 6 月 7 日:感谢 Los-Kos 的反馈,目前已修复文章页面目录不会展开的 BUG。

修改 themes/Butterfly/layout/post.pug 文件。这里我直接把整个文件放出来了,如果你没有修改过 post.pug,可以直接替换。

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
extends includes/layout.pug

block content
article#post(class="")
.post-timecount
include includes/post/timecount.pug
#article-container.post-content!=page.content
include includes/post/post-copyright.pug
.tag_share
if (theme.post_meta.post.tags)
.post-meta__tag-list
each item, index in page.tags.data
a(href=url_for(item.path)).post-meta__tags #[=item.name]
!=partial('includes/share/index', {}, {cache:theme.fragment_cache})

if theme.reward.enable
!=partial('includes/post/reward', {}, {cache:theme.fragment_cache})

//- ad
if theme.ad && theme.ad.post
.post-ad!=theme.ad.post

include includes/pagination.pug
if theme.related_post && theme.related_post.enable
!= related_posts(page,site.posts)
if page.comments !== false
include includes/comments/index.pug

好了,重新生成一下 hexo,看看效果。

hexo 时间久远文章提示