Search code examples
htmlgo-templates

Whitespaces aren't being trimmed Golang templates


In the following code, the white spaces aren't being trimmed despite using {{--}}

{{$first := true}}
{{range $name, $value := .Labels}}
  {{if $first}}
    {{$first = false}}
  {{else}}
    ,
  {{end}}
    {{$name}}={{$value -}}
{{end}}

So it prints like this: name=value , name2=value2

I'm not sure why the whitespaces aren't being trimmed... .Labels is a map[string]string and the strings don't have spaces in them, since the following:

{{range $name, $value := .Labels}}
  {{$name}}={{$value}},
{{end}}

prints without the leading space like this: name=value, name2=value2,


Solution

  • {{ $first := true -}}
    {{ range $name, $value := .Labels -}}
        {{ if $first -}}
            {{ $first = false -}}
        {{ else -}}
            {{- ", " -}}
        {{ end -}}
        
        {{ $name }}={{ $value -}}
    {{ end }}
    

    https://play.golang.org/p/0r69PUj3mEi