Split the CSV string into variables based on the table header

I would convert the CSV data to a slice of maps, then access the values via their key names.

layouts/_default/single.html
{{ $data := dict }}
{{ $p := "top.csv" }}
{{ with .Resources.GetMatch $p }}
  {{ $opts := dict "delimiter" ";" }}
  {{ with . | transform.Unmarshal $opts }}
    {{ $data = partial "csv-to-map.html" . }}
  {{ end }}
{{ else }}
  {{ errorf "Unable to get resource %q" $p }}
{{ end }}

{{ range $data }}
  <div>
    Place is: {{ .place }}
  </div>
  <div>
    Name is: {{ .name }}
  </div>
  <div>
    Money: {{ .money }}
  </div>
{{ end }}
layouts/partials/csv-to-map.html
{{ $headerRow := index . 0 }}
{{ $s := slice }}
{{ range . | after 1 }}
  {{ $m := dict }}
  {{ range $k, $v := . }}
    {{ $m = merge $m (dict (index $headerRow $k) $v) }}
  {{ end }}
  {{ $s = $s | append $m }}
{{ end }}
{{ return $s }}

Try it:

git clone --single-branch -b hugo-forum-topic-50473 https://github.com/jmooring/hugo-testing hugo-forum-topic-50473
cd hugo-forum-topic-50473
hugo server
1 Like