Yeah, that doesn’t work, sorry.
Short answer:
You should probably use a dictionary.
{{ .Page.Store.Add "all_sources" (slice (dict "destination" .Destination "text" .Text))}}
If you have only two values per render hook, and one of them is a string which will be unique per page, you can use .Store.SetInMap
instead.
<!-- In your render hook: -->
{{ .Page.Store.SetInMap "all_sources" .Destination .Text }}
<!-- Output your sources -->
{{ range $dest, $title := (.Store.Get "all_sources")}}
Title: {{ $title }}
URL: {{ $dest }}
{{end}}
If you want to use nested slices, you’ll need to add a slice within a slice the first time you call .Store.Add
, and then add a normal slice in all subsequent instances.
{{ if (.Scratch.Get "all-sources" }}
<!-- Value already exixts -->
{{ .Scratch.Add (slice .Destination .Text) }}
{{ else }}
<!-- Value doesn't exist yet -->
{{ .Scratch.Add (slice (slice .Destination .Text)) }}
{{ end }}
Longer answer:
The following comes from reading the source code for the relevant functions. I’m not a Go programmer, so it might not be correct, but it matches the behaviour I can see.
So the reason why my first suggestion didn’t work (and it probably requires a clarification in the docs, I’ll see if I can adjust it), is because .Scratch.Add
includes a bit of special handling to support both raw values and slices. Namely, it checks if the value exists, and whether the existing value is a slice. If it’s a slice, it runs the Append
function, if it’s not, it just adds the values together (so either addition or concatenation depending on type).
The Append
function also includes a bunch of special handling, as it can be used in two different ways: one or more values can be added to a slice, or two slices can be merged together. Since Go is statically typed, each of the values in the slice must be of the same type. The Append
function performs the following checks to determine how it operates:
- Is the target nil?
- Is the target a slice?
- Is the target a slice which contains other slices?
- Is there exactly one other argument to the function?
a. Is that one argument a slice?
If the target is nil, the function returns a slice made of the arguments. If the target is not a slice, the function throws an error. If the target does not contain other slices, and the single argument is a slice, then the values in the slice are appended.
If the target is a slice which contains other slices (the third check), then we get some of that special handling. The Append
function will check whether all other arguments passed to the function are also slices of a type compatible with the slices already in the target slice, and if they are, then it will append the slices directly to the target as it would any other raw value. It’s a sensible behaviour, but it’s not currently documented anywhere.