访问已排序的一对列表的第一个项目

huangapple go评论76阅读模式
英文:

Access first item of sorted pair list

问题

我是新手,正在尝试访问SortedPair列表中的第一个元素。我尝试了{{ (index .Labels.SortedPairs 1)}}{{ .Name }} = {{ .Value }},但是不起作用,我得到了can't evaluate field Name in type template.Alert的错误。

有没有办法获取第一个元素?当使用{{range}}时,它可以正常工作,但显示了太多元素。

谢谢。

英文:

I'm new to Go Templates and I'm trying to access the first element in a SortedPair list. I tried {{ (index .Labels.SortedPairs 1)}}{{ .Name }} = {{ .Value }} but that's not working, I'm getting can't evaluate field Name in type template.Alert.

Is there a way to get the very first element? When it's a {{range}}, it works fine but displays too many elements.

Thanks

答案1

得分: 2

请注意,第一个索引是0而不是1

您可以在显示其NameValue时对列表进行索引:

{{(index .Labels.SortedPairs 0).Name}} = {{(index .Labels.SortedPairs 0).Value}}

如果将其分配给变量,则会更简短:

{{$first := index .Labels.SortedPairs 0}}{{$first.Name}} = {{$first.Value}}

如果使用{{with}}操作,甚至更清晰:

{{with index .Labels.SortedPairs 0}}{{.Name}} = {{.Value}}{{end}}

让我们测试这3种变体:

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()
}

输出结果(在Go Playground上尝试):

first = 1
first = 1
first = 1
英文:

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

huangapple
  • 本文由 发表于 2017年4月6日 23:36:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/43259685.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定