如何在 HUGO 中获取 {{.GitInfo}}?

问题描述 投票:0回答:2

我想使用该内容文件的最后一次 git 提交日期来更新每个页面的“

Lastmod
”参数。所以我需要首先设置
"enableGitInfo = true"
,但是,当我在html中编码
'{{.GitInfo}}'
时,我得到了
'<nil>'
,并且
{{.Lastmod}}
打印了
'0001-01-01 00:00:00 +0000 UTC'

我在

config.toml
中写下如下:

enableGitInfo = true

[frontmatter]
date = ["date","lastmod"]
lastmod = [":git", "lastmod", "date"]
publishDate = ["publishDate", "date"]
expiryDate = ["expiryDate"]

我该怎么办?

hugo
2个回答
2
投票

事后看来,这似乎是显而易见的,但让我困惑的是,在

{{ .GitInfo }}
显示之前,您需要对该文件进行提交。

它正在提取与文件关联的数据,因此如果您移动文件或第一次创建文件,则需要提交才能填充该文件。

这是假设您有 Hugo 文档的要求:

  • Hugo 站点必须位于启用 Git 的目录中。
  • Git 可执行文件必须安装并位于您的系统路径中。
  • 必须在 Hugo 项目中启用 .GitInfo 功能,方法是在命令行上传递 --enableGitInfo 标志或在站点的配置文件中将
    enableGitInfo
    设置为 true (
    config.toml
    )。

您可能希望在模板中构建一些备份功能,以便在预览 Hugo 站点中尚未提交的页面时,您仍然可以看到日期:

{{ $date := now }}
{{ if .GitInfo }}
  {{ $date = .GitInfo.AuthorDate }}
{{ end }}

<div class="date">
  {{- $date.Format "January 02, 2006" -}}
</div>

1
投票

我成功创建了一个示例网站来测试这一点。看看这些步骤是否对您有帮助。

  1. hugo new site git-info-test
  2. cd git-info-test
  3. enableGitInfo = true
    添加到
    config.toml
    文件
  4. 创建
    layouts/index.html
    并添加
    {{.GitInfo | jsonify}}
  5. hugo new _index.md
  6. git init
  7. git add .
  8. git commit -m "Initial commit"
  9. hugo -D
  10. 您应该在生成的内容中看到类似的内容
    public/index.html
{
  "hash": "adf0bd47f37f413bf7c790a4c19c129cba6acf23",
  "abbreviatedHash": "adf0bd4",
  "subject": "Initial commit",
  "authorName": "John Smith",
  "authorEmail": "[email protected]",
  "authorDate": "2019-07-22T14:59:20-05:00"
}
© www.soinside.com 2019 - 2024. All rights reserved.