需更改文件的目录结构
tree . | ||
. | ||
├── _config.yml | ||
├── layout | ||
│ └── _partials | ||
│ └── layout.njk | ||
├── scripts | ||
│ └── generaters | ||
│ └── script.js | ||
└── source | ||
└── js | ||
└── _app | ||
├── global.js | ||
└── pjax.js |
添加到 source/js/_app/global.js
最后一行:
const isOutime = function(){ | |
if (CONFIG.outime.enable && LOCAL.outime) { | |
var times = document.getElementsByTagName('time'); | |
if (times.length === 0) { return; } | |
var posts = document.getElementsByClassName('body md'); | |
if (posts.length === 0) { return; } | |
var now = Date.now(); // 当前时间戳 | |
var pubTime = new Date(times[0].dateTime); // 文章发布时间戳 | |
if (times.length === 1) { | |
var updateTime = pubTime; // 文章发布时间亦是最后更新时间 | |
} else { | |
var updateTime = new Date(times[1].dateTime); // 文章最后更新时间戳 | |
} | |
var interval = parseInt(now - updateTime); // 时间差 | |
var days = parseInt(CONFIG.outime.days) || 30; // 设置时效,默认硬编码 30 天 | |
// 最后一次更新时间超过 days 天(毫秒) | |
if (interval > (days * 86400000)) { | |
var publish = parseInt((now - pubTime) / 86400000); | |
var updated = parseInt(interval / 86400000); | |
var template = ''; | |
if (!CONFIG.outime.template) { | |
template = '<div class="note warning"><p><span class="label warning">文章时效性提示</span><br>这是一篇发布于 '+publish+' 天前,最后一次更新在 '+updated+' 天前的文章,部分信息可能已经发生改变,请注意甄别。</p></div>'; | |
} else { | |
template = CONFIG.outime.template.replace('{{publish}}', publish).replace('{{updated}}', updated); | |
} | |
posts[0].insertAdjacentHTML('afterbegin', template); | |
} | |
} | |
} |
添加到 source/js/_app/pjax.js
的 siteRefresh
函数的最后一行:
cardActive() | |
lazyload.observe() | |
isOutime() // 判断文章时效性 |
添加到 scripts/generaters/script.js
的 siteConfig
变量中(具体哪一行没要求,加进去就行):
loader: theme.loader, | |
search : null, | |
outime: theme.outime, | |
valine: theme.valine, |
添加到 layout/_partials/layout.njk
的 LOCAL
变量中(我是加到 ignores
的上一行):
{%- if page.outime === false %} | |
outime: false,{%- else %} | |
outime: true, | |
{%- endif %} |
然后可以通过主题配置文件 _config.shoka.yml
控制:
# 文章是否失效 | |
outime: | |
enable: true | |
days: 30 # 超过 30 天文章失效 | |
template: '<div class="note warning"><p><span class="label warning">文章时效性提示</span><br>这是一篇发布于 {{publish}} 天前,最后一次更新在 {{updated}} 天前的文章,部分信息可能已经发生改变,请注意甄别。</p></div>' # 模板 |
对于单篇文章可以用 Front-matter
控制:
--- | |
outime: false #关闭检查文章是否失效 | |
--- |
效果:
文章时效性提示
这是一篇发布于 100 天前,最后一次更新在 30 天前的文章,部分信息可能已经发生改变,请注意甄别。