Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: range through slice and generate HTML table

Tags:

go

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?

like image 916
jwesonga Avatar asked Apr 05 '15 19:04

jwesonga


1 Answers

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.

like image 52
user4752457 Avatar answered Oct 17 '22 13:10

user4752457