next主题添加近期更新

在页面的左侧添加最近修改文章列表。这么基础的功能,next居然没有提供,只好自己动手了。

在/themes/next/layout/_macro/sidebar.njk 文件中最后一个 </aside> 之前添加:

  {% if theme.recent_posts.enable %}
<div class="links-of-blogroll">
<div class="sidebar-inner sidebar-recent-posts">
<div class="animated">
<div class="links-of-blogroll-title" style="margin-bottom: 10px; font-size: 18px;">
<!-- 选择合适的icon -->
{%- if theme.recent_posts.icon %}<i class="{{ theme.recent_posts.icon }}" aria-hidden="true"></i>{%- endif %}
{{ theme.recent_posts.description }}
</div>
<ul class="links-of-blogroll-list">
<!-- 文章排序规格,-updated 按照文章更新时间倒排 -->
{% set posts = site.posts.sort('-updated').toArray() %}
<!-- 显示四条近期文章 -->
{% for post in posts.slice('0', '5') %}
<li>
<a href="{{ url_for(post.path) }}" title="{{ post.title }}" target="_blank">{{ post.title }}</a>
</li>
{% endfor %}
</ul>
</div>
</div>
</div>
{% endif %}

在next主题的配置文件 _config.yaml 中,最后添加:

# 近期文章配置  
recent_posts:
enable: true
icon: fas fa-history
description: 近期更新

这样就可以使用了,文章还是按照创建时间排序,但这个最近更新会根据修改时间排序。

原先偷懒,文章中都没有标注更新时间,为了给文章全部添加修改时间字段,让ai写了个脚本,保存为 add_updated_field.sh 更改下运行权限 chmod +x add_updated_field.sh,直接运行./add_updated_field.sh 就一次全部添加了,发现使用ai最爽的就是让他写脚本,脚本这个语言简直反人类,使用ai是最合适了,又快又好。

#!/bin/bash

# --- 配置项 ---
# 要处理的文件扩展名,用空格分隔
FILE_EXTENSIONS="md markdown"
# 备份文件后缀名
BACKUP_SUFFIX=".bak"
# --- 配置项结束 ---

echo "--- 开始检查和添加 updated 字段 ---"
echo "处理的文件类型: ${FILE_EXTENSIONS}"
echo "------------------------------------"

# 构建 find 命令的 -name 参数
find_args=""
for ext in $FILE_EXTENSIONS; do
if [ -n "$find_args" ]; then
find_args="$find_args -o" # 使用 OR 连接符
fi
find_args="$find_args -name \"*.$ext\""
done

# 使用 eval 来正确执行包含引号的 find 命令
eval find . -type f $find_args | while IFS= read -r file; do

# 快速检查:文件是否包含 "date:" 并且不包含 "updated:"
# 只检查文件的前10行,提高效率
if head -n 10 "$file" | grep -q "^date: " && ! head -n 10 "$file" | grep -q "^updated: "; then

echo "正在处理文件: $file"

# 1. 提取 date 字段的值
# 使用 grep 找到 date 行,然后用 sed 去掉 "date: " 前缀
date_val=$(grep "^date: " "$file" | sed 's/^date:[ \t]*//')

# 2. 使用 sed 在 date: 行后面添加 updated: 行
# sed 的 "-i" 选项会直接修改文件,并创建备份
# a\ 表示在匹配行之后(after)追加内容
sed -i"$BACKUP_SUFFIX" "/^date: /a updated: $date_val" "$file"

echo " - 已添加 updated 字段。备份文件为 ${file}${BACKUP_SUFFIX}"

else
# 为了不让输出太冗长,可以注释掉下面这行
echo "跳过文件 (已存在 updated 或无 date): $file"
fi
done

echo "--- 脚本运行完毕 ---"