Hugo Stack 主题自动添加文章更新时间

English

其实hugo stack这个主题是默认支持显示文章更新时间的,相关代码在 layouts/partials/article/componets/footer.html

{{- if ne .Lastmod .Date -}}
<section class="article-lastmod">
    {{ partial "helper/icon" "clock" }}
    <span>
        {{ T "article.lastUpdatedOn" }} {{ .Lastmod | time.Format ( or .Site.Params.dateFormat.lastUpdated "Jan 02, 2006 15:04 MST" ) }}
    </span>
</section>
{{- end -}}

这段代码很好理解,如果文章配置了lastmod字段,就会在文章结尾的位置显示最后更新时间。但是这样有点麻烦,更新了文章还要手动修改lastmod时间,我决定读取git的文件提交时间。

Update config.yaml

只需要给你的config.yaml配置文件增加以下配置就可以实现自动读取git提交时间,这里面的配置大概是两个作用,enableGitInfo 开启git文件信息,然后 lastmod 先读取文章内的信息,没有的话读取git信息,最后读取 date 信息。

frontmatter:
  lastmod:
    - "lastmod"    # 优先使用 frontmatter 里的 lastmod
    - ":git"       # 如果没有 lastmod,则使用 Git 提交时间
    - "date"       # 最后 fallback 到 date 字段

enableGitInfo: true

Cloudflare pages

然而你部署到 cloudflare/github 之后你会发现所有文章的更新时间都是最后一次提交的git时间,是因为这些CI/CD平台只会读取最新的一条提交记录,解决方法很简单: 在cloudflare pages 修改部署命令拉取更多记录:

git fetch --unshallow && hugo

github workflows添加fetch-depth参数:

- uses: actions/checkout@v3
    with:
      fetch-depth: 0

修改显示位置

默认的更新时间会显示在文章最下方,我是改到了标题下方会更显眼,读者一点进来就能知道这篇文章是否完全过时了: 修改 layouts/partials/article/componets/details.html 插入这段代码:

{{- if ne .Lastmod .Date -}}
  <div>
      {{ partial "helper/icon" "date" }}
    <time class="article-time--published">
            {{ T "article.lastUpdatedOn" }} {{ .Lastmod | time.Format ( or .Site.Params.dateFormat.lastUpdated "Jan 02, 2006 15:04 MST" ) }}
    </time>
  </div>
{{- end -}}
加载中...
📊 加载中...
感谢Jimmy | 隐私政策 | 赞赏支持
Liu 的 AI 助手