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?