Golang separating items with comma in template

后端 未结 3 1003
感情败类
感情败类 2021-02-02 06:44

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:<

3条回答
  •  抹茶落季
    2021-02-02 06:59

    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

提交回复
热议问题