I see dict
, slice
or ""
used in defining variables. When or where should each be used?
{{ $data := dict }}
{{ range foo }}
{{ $data = bar }}
{{ end }}
I see dict
, slice
or ""
used in defining variables. When or where should each be used?
{{ $data := dict }}
{{ range foo }}
{{ $data = bar }}
{{ end }}
The short answer is: In most cases it doesn’t matter, just pick a falsy value (e.g. “”). Then you can do:
{{ $data := "" }}
{{ range $foo }}
{{ $data = . }}
{{ end }}
{{ with $data }}
{{ . }}
{{ end }}
But in some cases it matters, e.g:
{{ $data := slice }}
{{ range $foo }}
{{ $data = $data | append . }}
{{ end }}
{{ range $data }}
{{ . }}
{{ end }}
Alright. I asked mostly because with dict
or ""
, data is still returned here
{{ $data := dict }}
{{ $p := "data/books.json" }}
{{ with resources.Get $p }}
{{ $data = . | transform.Unmarshal }}
{{ else }}
{{ errorf "Unable to get resource %q" $p }}
{{ end }}
In the above example, $data
will either end up as a string or a map
, depending on if the resource is found or not, which in your case does not matter.
Sometimes I favor to initialize with nil
:
{{ $data := index dict "" }}
Not very readable, but it’s an option.
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.