Go template that properly renders delimiters for a slice of structs

It is common to write go text/templates that range over a slice of objects to write out a list or array of items that are separated by some delimiter defined in the template.

In the case of a JSON array of objects, the cleanest output would be a , separating each object without a leading or trailing comma.

Because go template if statements are falsey in that a 0 value will evaluate to false you can write a template as follows and it will only render a comma between items as it ranges over the slice

  {{- range $index, $item := .Items -}}
    {{- if $index -}},{{ end }}
      "id": {{ $item.Id }}, "name": {{ $item.Name }}
    {{- end }}

Click here for a working example.

Leave a Reply