Iterate over scratch

I am trying to iterate over a scratch variable and get all keys and values that are stored in it. My problem here is that whenever I try to iterate over the variable I get the following error message.

range can’t iterate over {map[apples:50 oranges:1 bananas:83 avocados:51 figs:33] {{0 0} 0 0 0 0}}

The error message results from the following code:

{{ range $key, $value := $scratch }}
   <p> {{ $key }}: {{ $value }} </p>
{{ end }}

The $scratch variable was created like this:

{{  $scratch := newScratch  }}
{{  $scratch.Set "apples" 50)  }}
{{  $scratch.Set "oranges" 1)  }}
{{  $scratch.Set "bananas" 83)  }}
{{  $scratch.Set "avocados" 51)  }}
{{  $scratch.Set "figs" 33)  }}

My Question here is the following: How can I iterate over scratch and get the key/values pairs?

What is $scratch? You are obviously not showing the full template.

I edited my question.

You are creating multple different scatches and attaching them to your variable. I guess .Scratch.SetInMap is what you are looking for. See the docs here. So try {{ .Scratch.SetInMap "fruits" "apples" 50 }} etc.

2 Likes