[Solved] CSV data key lookup

@yeehaa, I had similar troubles using getCSV as you found my post in your search, Range over getCSV array not iterating. I’m sorry if my explanation didn’t help you there.

To follow up with what I learned, it seems that the getCSV function reads the .csv file into an array, with each segment split by the character delimiter you specify, in your example the comma is used "," as the delimiter. this array can be ranged over, but in a csv file like the example you gave, it seems you want to first split the csv file up by row. Rows are not separated by commas, so you will first need to separate by carriage return which is "\r".

{{ range $i, $r := getCSV "\r" "/abc.csv" }}
{{ end }}

After separating the csv into the array you created (containing row data), you will then need to split them up into each column of that row to find the data you want to match (individual cell data from the first column of the row) The data separated by rows is in the array as a string, so it can be divided using the split function with the comma "," as the delimiter.

{{ range $i, $r := getCSV "\r" "/abc.csv" }}
{{ $c := split (index . 0) "," }} 
{{ end }}

This will then get you access to the data read from each cell of that row using index to get to the substrings made by split. From there you can check to see if the data in the first column (with the index key 0 of the slice) has the data that matches your key variable (in the front matter) for that row in the range. To do this simply we can use a conditional statement to see if it is equal, and if it is not, continue to the next row.

{{ range $i, $r := getCSV "\r" "/abc.csv" }}
{{ $c := split (index . 0) "," }} 
{{ if eq $.Params.id (index $c 0) }}
{{ end }}
{{ end }}

Once the row is found you will want to output the contents of each cell from that row to your page, so you can use the html from your example to do that, within the range, after the split as shown below:

{{ range $i, $r := getCSV "\r" "/abc.csv" }}
{{ $c := split (index . 0) "," }} 
{{ if eq $.Params.id (index $c 0) }}
 <div class = "{{ index $c 4 }}">
 <span> {{ index $c 0 }}</span>
 <span> {{ index $c 1 }}</span>
 <span> {{ index $c 2 }}</span>
 <span> {{ index $c 3 }}</span>
 </div>
 <img src = "{{ index $c 5}}">
{{ end }}
{{ end }}

I hope that this helps you solve the problem that you are having, or at least help you understand what I learned more completely so you can figure out the solution.