Golang separating items with comma in template

A nice trick you can use is:

Equipment:
    {{$equipment := .Equipment}}
    {{ range $index, $element := .Equipment}}
        {{if $index}},{{end}}
        {{$element.Name}}
    {{end}}

This works because the first index is 0, which returns false in the if statement. So this code returns false for the first index, and then places a comma in front of each following iteration. This results in a comma separated list without a leading or trailing comma.


Add a template function to do the work for you. strings.Join is perfect for your use case.

Assuming tmpl contains your templates, add the Join function to your template:

tmpl = tmpl.Funcs(template.FuncMap{"StringsJoin": strings.Join})

Template:

Equipment:
    {{ StringsJoin .Equipment ", " }}

Playground

Docs: https://golang.org/pkg/text/template/#FuncMap

Tags:

Go