Render a string as a "hugo command"

tl:dr : Can i compose a “hugo path” with strings passed as variables in the path ?

I have this :

(I fetch a specific data file going through my folder structure : Data → myPartial → en → mydata.yml)
index.html

{{ partial "myPartial" (dict "ctx" . "data" (index .Site.Data.myPartial .Site.Language.Lang).mydata) }}

(then i access my data in a {{ with .data }} statement)
myPartial.html

{{ with .data }}
  <div>
    <h3>{{ .title }}</h3>
    <p>{{ .text }}</p>
  </div>
{{ end }}

I would like to get this :

(I just indicate the file name in the key/value “data” → partial declaration gets dryer)
index.html

{{ partial "myPartial" (dict "ctx" . "data" "mydata") }}

(then i access my data in a “recomposed hugo path”)
myPartial.html (PSEUDO code)↓

{{ with (index (printf site.Data.%s (hugorender "myPartial")) (printf .site.Language.Lang).%s  (hugorender "data")) }}
  <div>
    <h3>{{ .title }}</h3>
    <p>{{ .text }}</p>
  </div>
{{ end }}

In essence “hugorender” would convert a string to an understandable “hugo command” at build time, i hope i’m clear.

What i’m asking is : is there an already possible way to do that (maybe with slice or delimit), or maybe i’ve overlooked something simple ?
Or is this idea in contradiction with how Hugo and Go fondamentaly works ?

Thanks for reading me !

PS : I know i can do {{ with (index .Site.Data.myPartial .Site.Language.Lang).mydata }} in myPartial but what if i have multiple myPartial calls and multiple data files as sources ? Hence my post

The index function is variadic —it accepts a variable number of arguments.

{{ partial "my-partial" (dict "ctx" . "data" "my-data") }}

layouts/partials/my-partial.html

{{ $partialName := "my-partial" }}
{{ with index site.Data $partialName .ctx.Language.Lang .data }}
  <h3>{{ .title }}</h3>
  <p>{{ .text }}</p>
{{ end }}

You could just use the string literal “my-partial” in the index function, but sometimes I find it useful to initialize a var, as shown above. That way I can include it in error or warning messages. While shortcodes know their own name (via the .Name method), other templates do not.

1 Like

Thanks a lot for answering, this worked !!

I was handling the index function incorrectly and did not know you could add many parameters without parenthesis like that, i learned what variadic means today :face_with_monocle: thank you !

Heads up for anyone reading/using this :
You have to populate ALL your data folders, even with an empty .yml otherwise the index will return “index of nil pointer” when indexing.
data

This community feels great, and gives me confidence to further develop websites using Hugo.
I have the utmost respect for you guys, the feeling is like walking among giants.

Have a good day

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