Passing Vars to Paritals & Scope

So unfortunately the simple answer to doing this isn’t the anywhere in the top results, so from buried in the docs:

Use a dictionary to pass vars to a partial:

{{ partial "myPartial.html" (dict "key1" "value1" "key2" $value2) }}

Now for related question. To access the variables in the partial you use the form {{ .key1 }}. Simple enough.

But what I don’t understand is why does that variable become undefined inside a range in the partial? Ex:

myPartial.html:

{{ .key1 }} // works fine
{{ range $currItem := .key2 }} // this also works for key2
  {{ .key1 }} // but now key1 is null
  {{ $.key1 }} // but with the $. notation, it works.
{{ end }}

Why?

Hi,

Have a read here about the dot context: https://gohugo.io/templates/introduction/#the-dot

Ahh, missed this one bit of it:

Inside of an iteration, however, it will have the value of the current item in the loop; i.e., {{ . }} will no longer refer to the data available to the entire page.

I was thinking of it like a more typical programming loop, its iteration variables wouldn’t live outside the loop, but the vars from before the loop would be in it’s scope. My bad

Thanks!

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