Pass parameters to functions

I have a call in one of my single.html template files to this:

{{ $code := partial "'directory/code.html" . }}
{{ highlight $code "html" "" }}

which reads the file correctly and outputs highlighted code. However, how do I pass in the {{ .Params.slug }} from my content to that function, so as to dynamically alter that partial directory path? Something like (but not, I know):

{{ $a := partial "'components/{{ .Params.slug }}.html" . }}

Thank you!

Try printf:

{{ $a := (partial (printf "'components/%s.html" .Params.slug) .) }}

You cannot have nested curly bracesā€¦ recent, related

1 Like

Thank you for the help!

Unfortunately that is returning:

error calling partial: Partial "'directory/%!s(<nil>).html" not found

when using

{{ $a := partial (printf "'directory/%s.html" .Params.slug) . }}

Is it related to the single quote mark?

I have no idea why you had that in the first placeā€¦ I assumed that for some odd reason, you directory name began with ', so I left it there ā€¦

One of your files doesnā€™t have that .Params.slug setā€¦ so thatā€™s returning nilā€¦ what you are seeing is because nil is trying to get printed using the %s.

Assuming that you have a default partial called components/foo.html, you can do:

{{ $a := (partial (printf "components/%s.html" (.Params.slug | default "foo")) .) }}

Then that default partial will be used if your .Params.slug is not set.

Btw, do you really intend to have a unique partial for each slug?

Just making sure that you are aware of the special meaning of slug in front-matter.

Thanks for the catch on the single quote, I didnā€™t notice it was my typo.

I was perhaps not using slug correctly, so Iā€™ve changed to ā€˜nicknameā€™ as set in my contentā€™s front-matter. (though yes, I am going to have a unique partial for each slug, Iā€™m using Hugo for a pattern library website and the partials are the patterns Iā€™m referencing to pull in to the page)

Iā€™m able to call

{{ .Params.nickname }}

Just fine earlier in the template, so Iā€™m not sure why itā€™s not getting that here and returning nil instead?