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.