How to index a slice element?

依然范特西╮ 提交于 2020-12-28 04:29:47

问题


I have a slice: Keys []* datastore.Key

How could I index one of them in the template file? I guessed {{.Keys[3] }}, but that doesn't work and I searched a lot but with no clue.

Any suggestions would be welcome, thanks.


回答1:


Use the index command like so:

{{index .Keys 3}}



回答2:


As stated in the html/template package, the majority of examples are actually located in the text/template pkg docs. See http://golang.org/pkg/text/template/

From the docs

index
    Returns the result of indexing its first argument by the
    following arguments. Thus "index x 1 2 3" is, in Go syntax,
    x[1][2][3]. Each indexed item must be a map, slice, or array.


来源:https://stackoverflow.com/questions/12701452/how-to-index-a-slice-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!