'Golang separating items with comma in template

I am trying to display a list of comma separated values, and don't want to display a comma after the last item (or the only item if there is only one).

My code so far:

Equipment:
    {{$equipment := .Equipment}}
    {{ range $index, $element := .Equipment}}
        {{$element.Name}}
        {{if lt $index ((len $equipment) -1)}}
            ,
        {{end}}
    {{end}}

The current output: Equipment: Mat , Dumbbell , How do I get rid of the trailing comma

go


Solution 1:[1]

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

Solution 2:[2]

Another way to skin the cat, if you can create a new type for the field.

type MyList []string

func (list MyList) Join() string {
    return strings.Join(list, ", ")
}

Then you can use the function in the template like regular:

{{ .MyList.Join }}

Solution 3:[3]

If you are willing to use an external library, it seems like sprig library has a "join" function (see here):

join

Join a list of strings into a single string, with the given separator.

list "hello" "world" | join "_"

The above will produce hello_world

join will try to convert non-strings to a string value:

list 1 2 3 | join "+"

The above will produce 1+2+3

Solution 4:[4]

without index

it can be useful for any iteration like on maps that do not have index:

    {{ $first := true }}
    {{ range $index, $element := .}}
        {{if not $first}}, {{else}} {{$first = false}} {{end}}
        {{$element.Name}}
    {{end}}

Playground

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2
Solution 3 Elouan Keryell-Even
Solution 4 Pierre Louis