实现原理

Hugo有一个.GitInfo变量,会返回最后一次commit的hash、时间等数据

模板集成

找到如下文件,添加或修改其内容

config.toml

enableGitInfo = true                        # 启用GitInfo支持

[frontmatter]
 lastmod = ["lastmod", ":git", "date"]      # 按顺序依次获取,直到返回结果

single.html

<time datetime="{{ .Page.Lastmod.Format "2006-01-02 15:04:05 MST" }}" class="post-date">
    Last Updated {{ .Page.Lastmod.Format "2006-01-02" }}
    {{ with .GitInfo }}
    By {{ .AbbreviatedHash }}
    {{ end }}
</time>

遇到问题

.GitInfo变量返回<nil>,并且这种问题只出现在以中文命名的.md文件中,猜测与编码有关

解决方法

个人电脑

使用git config core.quotePath false修改Git配置,禁止使用反斜杠转义字符

Vercel

  1. 进入项目主页
  2. 导航到settings -> general -> Build & Development Settings
  3. INSTALL COMMAND中输入git config core.quotePath false
  4. 打开OVERRIDE

参考链接

  1. https://rac.su/hugo/gitinfo/

  2. https://github.com/gohugoio/hugo/issues/3071

  3. https://github.com/peaceiris/actions-hugo/issues/496