detect last item inside an array using range inside go-templates

无人久伴 提交于 2019-12-01 17:28:41

You can use

tpl := "{{range $i, $el := .items}}{{if $i}},{{end}}{{$el}}{{end}}."

to achieve that. The trick is to emit the comma separator first, but not for the first item in the range.

In the simple example you posted, easiest is what "fhe" posted: you can easily check if the current index is the first, and output a comma after non-first elements. And finally output a trailing dot.

If in a more complicated example you do need to detect the last item, or it may be that the list you iterate over may be empty (and thus the trailing dot would be a mistake), you may register a custom function to tell if the current index is the last:

lister := template.Must(template.New("foo").Funcs(template.FuncMap{
    "IsLast": func(i, size int) bool { return i == size-1 },
}).Parse(tpl))

And use the following template then:

tpl := "{{range $i, $el := .items}}{{$el}}{{if IsLast $i (len $.items)}}.{{else}},{{end}}{{end}}"

Then the output will be (try it on the Go Playground):

1,4,2.

A variation of this could be to register a custom function which calculates the last index from the length (lastIdx = length - 1), and then inside the {{range}} you can do a simple comparison:

tpl := "{{$lastIdx := LastIdx (len .items)}}{{range $i, $el := .items}}{{$el}}{{if eq $lastIdx $i}}.{{else}},{{end}}{{end}}"
lister := template.Must(template.New("foo").Funcs(template.FuncMap{
    "LastIdx": func(size int) int { return size - 1 },
}).Parse(tpl))

Output will be the same. Try it on the Go Playground.

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