Question about implementation

I want to display a last updated time on a post, and link it back to the git commit hash. So I have something like Latest revision: <a href="https://github.com/willduncanphoto/willduncan.com/commit/{{ .GitInfo.Hash }}">{{ partial "apstyle_datetime.html" .Lastmod }}</a>

But when I build a new post, this causes the hugo server rendering the page to kick back and error.

Change detected, rebuilding site.
2022-01-10 21:57:27.043 -0800
Source changed "/Users/snoop/Lab/willduncan.com/content/posts/two.md": WRITE
ERROR 2022/01/10 21:57:27 Rebuild failed:

ERROR 2022/01/10 21:57:27 Failed to render pages: render of "page" failed: "/Users/snoop/Lab/willduncan.com/themes/basic/layouts/_default/single.html:18:108": execute of template failed: template: _default/single.html:18:108: executing "main" at <.GitInfo.Hash>: nil pointer evaluating *gitmap.GitInfo.Hash
Total in 40 ms

So it kicks back an error if no githash is present?

Would I just want to clear the entire line if there is no data?

You need to check for the existence of the .GitInfo.Hash.

For example
.../commit/{{ with .GitInfo.Hash }}{{ . }}{{ end }}

It is recommended to perform such checks in Go templates, so that the nil error can be avoided.

See: with | Hugo

1 Like

No dice on the first attempt based on what you suggested. I just found Using GitInfo - #5 by RickCogley but haven’t had time to read it.

The problem is, that if you hand us one single line of code to solve your problem you get an answer according to what we see. What you don’t say is if your layout is aware of the existence of .GitInfo at that point or not. Because if a file is NOT part of the repo yet (you just added it and did not create a commit yet), then it has no GitInfo. So obviously .GitInfo.Something can’t exist if .GitInfo does not exist and checking for a subkey’s existence fails if the parent key does not exist.

Either show the full layout for a post and/or check, that Git is configured in your repo and ALL pages have Information available for what you try to implement because they ALL are checked and it might be a completely different page than the one you are working on that throws the error.

Do this:

{{ with .GitInfo }}{{ .Hash }}{{ end }}

Not this:

{{ with .GitInfo.Hash }}{{ . }}{{ end }} --> error if .GitInfo is nil
2 Likes

Thanks @jmooring!

Took a little tweaking, cause .LastMod was kicking back an error.

{{ with .GitInfo }}<span>Latest revision: <a href="https://github.com/willduncanphoto/willduncan.com/commit/{{ .Hash }}">{{ partial "apstyle_datetime.html" .AuthorDate }}</a> by {{ .AuthorName }}{{ end }} seems to work.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.