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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With