Golang separating items with comma in template

后端 未结 3 997
感情败类
感情败类 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

    0 讨论(0)
  • 2021-02-02 07:12

    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

    0 讨论(0)
  • 2021-02-02 07:22

    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.

    0 讨论(0)
提交回复
热议问题