Note that the first index is 0
and not 1
.
You may index the list both when displaying its Name
and Value
:
{{(index .Labels.SortedPairs 0).Name}} = {{(index .Labels.SortedPairs 0).Value}}
It's shorter if you assign it to a variable though:
{{$first := index .Labels.SortedPairs 0}}{{$first.Name}} = {{$first.Value}}
And even clearer if you use the {{with}}
action:
{{with index .Labels.SortedPairs 0}}{{.Name}} = {{.Value}}{{end}}
Let's test the 3 variants:
type Pair struct {
Name, Value string
}
var variants = []string{
`{{$first := index .SortedPairs 0}}{{$first.Name}} = {{$first.Value}}`,
`{{(index .SortedPairs 0).Name}} = {{(index .SortedPairs 0).Value}}`,
`{{with index .SortedPairs 0}}{{.Name}} = {{.Value}}{{end}}`,
}
m := map[string]interface{}{
"SortedPairs": []Pair{
{"first", "1"},
{"second", "2"},
},
}
for _, templ := range variants {
t := template.Must(template.New("").Parse(templ))
if err := t.Execute(os.Stdout, m); err != nil {
panic(err)
}
fmt.Println()
}
Output (try it on the Go Playground):
first = 1
first = 1
first = 1