jwesonga
jwesonga

Reputation: 4383

Golang: range through slice and generate HTML table

I have a string slice, I'd like to range through the slice and create a simple HTML table with the values. This is some sample code to illustrate:

var tmpl = `<td>%s</td>`
names := []string{"john", "jim"}
    for _, v := range names {
      fmt.Printf(tmpl, v)
    }

This produces:

<td>john</td><td>jim</td>

I'd like to take what's returned and create a HTML table or at least be able to pass it to another HTML template that has the table structure. Any ideas how this can be done?

Upvotes: 5

Views: 7951

Answers (1)

user4752457
user4752457

Reputation: 206

Here's one way to create a table:

var tmpl = `<tr><td>%s</td></tr>`
fmt.Printf("<table>")
names := []string{"john", "jim"}
for _, v := range names {
      fmt.Printf(tmpl, v)
}
fmt.Printf("</table>")

You can also use the html/template package:

t := template.Must(template.New("").Parse(`<table>{{range .}}<tr><td>{{.}}</td></tr>{{end}}</table>`))
names := []string{"john", "jim"}
if err := t.Execute(os.Stdout, names); err != nil {
  log.Fatal(err)
}

I do not have enough juice to answer the question in OP's comment above, so I'll answer it here.

A template takes a single argument. If you want to pass multiple values to a template, then create a struct to hold the values:

 var data struct{ 
    A int
    Names []string
 }{
    1,
    []string{"john", "jim"},
 }
 if err := t.Execute(os.Stdout, &data); err != nil {
   log.Fatal(err)
 }

Use {{.A}} and {{.Name}} in the template.

Upvotes: 8

Related Questions