Go template remove the last comma in range loop

孤人 提交于 2019-11-30 19:36:32

Here's how to write comma separated key-value pairs using a template function.

Declare a function that returns a function that increments and returns a counter:

func counter() func() int {
    i := -1
    return func() int {
        i++
        return i
    }
}

Add this function to the template:

t := template.Must(template.New("example").Funcs(template.FuncMap{"counter": counter}).Parse(temp))

Use it in the template like this:

    {{$c := counter}}{{range $key, $value := $}}{{if call $c}}, {{end}}key:{{$key}} value:{{$value}}{{end}}

This template writes the separators before the key-value pairs instead after the pairs.

The counter is created before the loop and incremented on each iteration through the loop. The separator is not written the first time through the loop.

Run it in the playground.

The logic in the template can be simplified by moving the if statement to Go code:

func separator(s string) func() string {
    i := -1
    return func() string {
        i++
        if i == 0 {
            return ""
        }
        return s
    }
}

Add the function to the template:

t := template.Must(template.New("example").Funcs(template.FuncMap{"separator": separator}).Parse(temp))

Use it like this:

{{$s := separator ", "}}{{range $key, $value := $}}{{call $s}}key:{{$key}} value:{{$value}}{{end}}

Run it on the playground.

Since Go 1.11 it is now possible to change values of template variables. This gives us the possibility to do this without the need of a custom function (being outside of the template).

The following template does that:

{{$first := true}}
{{range $key, $value := $}}
    {{if $first}}
        {{$first = false}}
    {{else}}
        ,
    {{end}}
    key:{{$key}} value:{{$value}}
{{end}}

Here's the altered working example from the question:

type Map map[string]string
m := Map{
    "a": "b",
    "c": "d",
    "e": "f",
}
const temp = `{{$first := true}}{{range $key, $value := $}}{{if $first}}{{$first = false}}{{else}}, {{end}}key:{{$key}} value:{{$value}}{{end}}`
t := template.Must(template.New("example").Parse(temp))
t.Execute(os.Stdout, m)

Which outputs (try it on the Go Playground):

key:a value:b, key:c value:d, key:e value:f
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!