Problem: I want to create a table for each post whose contents changes for each post. The relevant data is in a YAML file located in /data/mydata.yaml. The table will be constructed using a shortcode.
Here is the data, for example:
- 01:
category1
- item1
- item 2
category2
- item 1
- item 2
- item 3
- 02
category1
- item1
- item 2
category2
- item 1
- item 2
- item 3
My shortcode works like so
{{< myshortcode "01" >}}
What I want to do is range over the category values only for the data set passed through the shortcode, the ‘01’ or ‘02’ or ‘03’… etc.
Now I know to write something like the following:
{{ range .Site.Data.mydata }}
I’ve tried different things, but I cannot get it to return me only the data I want, so that I can range over .category1 and .category2, like so
{{ range .category1}}
{{ . }}
{{ end }}
Thanks for any help.
Your data sample is not valid yaml, and I don’t know if this is a typo. I don’t know what your actual data looks like.
Assuming you meant something like this:
- 01:
category1:
- item 1
- item 2
category2:
- item 1
- item 2
- item 3
- 02:
category1:
- item 1
- item 2
category2:
- item 1
- item 2
- item 3
you need to do something like this:
{{ range $data }}
{{ range $k1, $v1 := . }}
{{ if eq $k1 "1" }}
<h2>{{$k1}}</h2>
{{ range $k2, $v2 := $v1 }}
{{ $k2 }}: {{ $v2 }}
<br>
{{ end }}
{{ end }}
{{ end }}
{{ end }}
Which, given my assumed data, will output this:
1
category1: [item 1 item 2]
category2: [item 1 item 2 item 3]
Thanks for the advice. It’s inching me where I want to go.
Edit 3: Decided to trim leading “0” instead and stick with int.
Edit 2: Updated the code a little. Changed from int to string for purpose of comparison due to the way Hugo int deals with numbers that have a ‘0’ in front of them (treating them as octals).
Edit: Oh yeah… thanks!
So it appears to be working. You were right about the datafile.
Here is what is working for me (the $match math is due to $k1 being out of sync):
{{ $documentnumber := int (( .Get 0) | string.TrimLeft "0" ) }}
{{ range $k1, $v1 := .Site.Data.mydata }}
{{ $match := (add $k1 1) }}
{{ if eq $match $documentnumber }}
<table>
{{ range .category1 }}
<tr>
<td>{{.}}</td>
</tr>
{{ end }}
</table>
{{ end}}
{{ end }}