readFile printf not working inside partial

Hi guys,

I am having a hell of a time figuring this out.

In my /content/blog/ frontmatter I have param: authorBio.id

This may or may not exist.

This id corresponds to a file in /content/authors/{id}.md

Inside /layouts/partials/ I need to:

  1. Look for the presence of this param
  2. If it exists, readFile from the corresponding /content/authors/{id}.md
  3. Output a value from that file

This is what I have tried:

{{ with .Params.authorBio }}
{{ $authorName := (readFile (printf "authors/%s.md" (.Params.authorBio.id)) | transform.Unmarshal).name ) }}
{{ end }}

It is throwing the following error:

render of "page" failed: execute of template failed: template: blog/single.html:17:4: executing "blog/single.html" at <partial "meta.html" .>: error calling partial: execute of template failed: template: partials/meta.html:11:9: executing "partials/meta.html" at <readFile (printf "authors/%s.md" .Params.authorBio.id)>: error calling readFile: file "authors/%!s(<nil>).md" does not exist

I am unsure why "authors/%!s(<nil>).md" does not exist is being returned.

If I replace %s with a hardcoded id (string) that I know exists, it reads the file successfully. But using printf to concatenate the .Params.authorBio.id fails.

I am assuming the is on pages where no .Params.authorBio.id exists, however I thought the with block would prevent the $authorName variable assignment in those cases?

Any help will be much appreciated. Thanks all.

You have a context problem. See https://gohugo.io/functions/with

Rebinds the context ( . ) within its scope

This code

{{ with .Params.authorBio }}
  {{ .Params.authorBio.id }}
{{ end }}

Is trying to print the value of .Params.authorBio.Params.authorBio.id

Ah geez of course it does. Thanks @jmooring.

For anyone reading in future, the solution was to change my variable assignment to:

{{ $authorName := (readFile (printf "authors/%s.md" (.id)) | transform.Unmarshal).name }}

:man_facepalming:t3:

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