'Go template remove the last comma in range loop
I have code like this:
package main
import (
"text/template"
"os"
)
func main() {
type Map map[string]string
m := Map {
"a": "b",
"c": "d",
}
const temp = `{{range $key, $value := $}}key:{{$key}} value:{{$value}},{{end}}`
t := template.Must(template.New("example").Parse(temp))
t.Execute(os.Stdout, m)
}
it will output :
key:a value:b,key:c value:d,
but I want something like this:
key:a value:b,key:c value:d
I don't need the last comma, how to remove it. I found a solution for looping an array here: https://groups.google.com/d/msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ , but I can't get index for a map.
Solution 1:[1]
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
Solution 2:[2]
I used the below template to correctly format some JSON using a go template.
It handles a collection of any size or empty.
{{- define "JoinList" -}}
{{- $lastIndex := math.Sub (len .) 1 -}}
{{- range $index, $property := . -}}
{{ if isKind "string" $property.value }}
"{{ $property.key }}": "{{ $property.value }}"{{ if ne $index $lastIndex }},{{ end }}
{{- else -}}
"{{ $property.key }}": {{ $property.value }}{{ if ne $index $lastIndex }},{{ end }}
{{ end }}
{{- end -}}
{{- end -}}
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 | icza |
| Solution 2 | Fergus |
