If the list is not empty, then the Python fragment prints a semicolon after the last element. You can achieve the same result in Go by surrounding the range if you need to check if there is at least one element in the slice and print it; out of cycle.
{{if $hosts}}{{range $host := $hosts}} {{$host}} {{ end }} ;{{end}}
This snippet works because you add it to the end of the last element. A more general solution requires a special template function. Here is an example function:
func last(v interface{}, i int) (bool, error) { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Slice { return false, errors.New("not a slice") } return rv.Len()-1 == i, nil }
and here is how to use it in a template:
{{range $i, $host := $hosts }} {{$host}}{{if last $hosts $i}} ;{{end}} {{ end }}
I posted a working example of a custom function on the playground.
source share