Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang separating items with comma in template

Tags:

go

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

like image 732
Lee Avatar asked Jan 23 '14 10:01

Lee


3 Answers

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.

like image 79
RobF Avatar answered Nov 16 '22 07:11

RobF


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

like image 39
jmaloney Avatar answered Nov 16 '22 09:11

jmaloney


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 }}
like image 1
Uranoxyd Avatar answered Nov 16 '22 07:11

Uranoxyd