I am trying to create an HTML template that includes a table. Each row in the table should represent a struct I have and include values from that struct.
The only relevant reference I found is this: golang template - how to render templates?
The difference is that I don't know in advance the number of rows in the table, so I need to be able to loop through a dyanmic list of structs I have, and for each such struct populate its values into a template representing a row and add that row to the parent template representing the table.
Can anyone show me how this can be done? Any other approach is also welcome.
I think you're just looking for {{range}}
, right? E.g.
package main
import "log"
import "os"
import "html/template"
type Highscore struct {
Name string
Score int
}
func main() {
const tpl = `<ol>
{{range .}}
<li>{{.Name}} - {{.Score}}</li>
{{end}}
</ol>
`
scores := []Highscore{
Highscore{"Steve", 50},
Highscore{"Jim", 40},
}
scoreTemplate, err := template.New("scores").Parse(tpl)
if err != nil {
log.Fatal(err)
}
err = scoreTemplate.Execute(os.Stdout, scores)
if err != nil {
log.Fatal(err)
}
}