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

【更新日志】优化hugo更新时间,自动读取git日期并显示在标题下方

其实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字段,就会在文章结尾的位置显示最后更新时间,格式是配置在config里面的Site.Params.dateFormat.lastUpdated。但是这样有点麻烦,更新了文章还要手动修改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 -}}
Licensed under CC BY-NC-SA 4.0
加载中...
感谢Jimmy 隐私政策