Range over string slice in golang template

JetThomas picture JetThomas · Jan 12, 2019 · Viewed 15.1k times · Source

I have a struct that contains a slice of type string like the following.

 type Data struct {
      DataFields []string
 }

Within my html template file I would like to range over the string slice. However, the individual fields are just strings without any struct name. How can I loop over a slice that contains a simple type such as string, int, etc?

Answer

Cerise Limón picture Cerise Limón · Jan 12, 2019

Use . to refer to a simple values like a string, int, etc.

 {{range .DataFields}}{{.}}{{end}}

Run it on the Playground.

You can also assign to a template variable as in {{range $v := .DataFields}}{{$v}}{{end}}, but that's extra work. Embrace the ..