Hi All,
I am passing a slice of data to a template. This slice can be any length from 1 - 6. Within the template I assign each slice to a variable via its index: {{$varName := index .sliceName 1}}.
I am trying to find a way to check if the index exists before assigning to the variable. I have tried {{ if index .sliceName 5 }} but get errors.
The end result I am aiming for is to only print a part of the template if an index of the slice exists.
I have a working solution, it may not be the most efficient, so any suggestions for improvement are welcome:
{{ range $Idx, $sample := .samples}}
{{ if eq $Idx 1}}
// Show template code for sample 1
{{end}}
{{ if eq $Idx 2}}
// Show template code for sample 2, if exists
{{end}}
{{ if eq $Idx 3}}
// Show template code for sample 3 if exists
{{end}}
{{end}}
// Some other template code here …
{{ range $Idx, $sample := .samples}}
{{ if eq $Idx 4}}
// Show template code for sample 4
{{end}}
{{ if eq $Idx 5}}
// Show template code for sample 5, if exists
{{end}}
{{ if eq $Idx 6}}
// Show template code for sample 6 if exists
{{end}}
{{end}}